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

本文介绍了如何使用MyBatis框架在插入数据时,配合MySQL的自增特性,获取新生成的ID。通过在`studentMapper.xml`中配置`useGeneratedKeys`和`keyProperty`,并将自增ID映射到`Student`类的`id`属性,实现了在`StudentMapper`接口中插入学生信息并获取自增ID的功能。在测试代码中展示了插入操作及打印自增ID的过程。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值