十三、自增处理(mysql)-Mybatis快速入门小白编

mybatis能够直接实现mysql数据库的自增,只用在studentMapper.xml中配置
useGeneratedKeys 使用自增
keyProperty 自增对应的类的属性

studentMapper.xml


    
        insert into student (name,age) values(#{name},#{age})
    

StudentMapper.java接口

public interface StudentMapper {
    //使用xml增加学生,实现自增返回
    void insertStudent(Student student);
}

TestMybatis.java

   //使用xml增加学生,实现自增返回
    public static void insertStudent() throws IOException {
        Reader resourceAsReader = Resources.getResourceAsReader("conf.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student();
        student.setName("ee");
        student.setAge(55);
        mapper.insertStudent(student);
        System.out.println(student.getId());
        System.out.println(student);
    }

输出结果:

8
8ee55

你可能感兴趣的:(十三、自增处理(mysql)-Mybatis快速入门小白编)