StudentMapper.xml

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <!--
    5. mapper:是个整体文件的大标签,用来开始和结束xml文件
    6. 属性: namespace指定命名空间(相当于包名)用来区分不同mapper.xml文件中相同的id属性
    7. -->
    8. <mapper namespace="zar">
    9. <!--
    10. 完成查询全部学生的功能
    11. 之前是List<Student> getAll();
    12. resultType:指定查询返回的结果集的类型,如果是集合则必须是泛型的类型
    13. parameterType: 如果有参数,则通过它来指定参数的类型
    14. -->
    15. <select id="getAll" resultType="org.pojo.Student">
    16. select * from student
    17. </select>
    18. <!--
    19. 按学生名模糊查询
    20. List<Student> getByName(String name);
    21. -->
    22. <select id="getByName" parameterType="string" resultType="org.pojo.Student">
    23. select * from student where name like '%${name}%'
    24. </select>
    25. <!--
    26. 增加学生
    27. int insert(Student stu);
    28. 实体类:
    29. private Integer id;
    30. private String name;
    31. private String email;
    32. private Integer age;
    33. -->
    34. <insert id="insert1" parameterType="org.pojo.Student">
    35. insert into student (name,email,age) values (#{name},#{email},#{age})
    36. </insert>
    37. </mapper>

    测试

    public class AppTest{
        @Test
        public void testInsertOne() throws IOException {
            InputStream in = Resources.getResourceAsStream("mybatis.xml");
    
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
            SqlSession sqlSession = factory.openSession();
            int num = sqlSession.insert("zar.insert1",new Student("wangwu","wangwu@qq.com",21));
            //切记切记切记: 在所有的增删改后必须手工提交事务!!!
            sqlSession.commit();
            sqlSession.close();
        }
    }
    

    前提是你设计的数据库要是id自增

    create table student1(id int not null unique auto_increment,name varchar(255) not null , email varchar(255) not null , age int not null );
    
    insert into student1(name, email, age) VALUES ("张三","zhangsan@qq.com",20);
    
    select * from student1;
    

    我目前的数据库要自己手动写id,就写出来了,反正就是上面加个id