赞
踩
一般来说,我们数据库的ID值都是设置的自动增长,所以在使用Mybatis时,我们添加记录时一般不会添加ID进去,但是我们确需要知道我们添加的记录ID是多少,这时候就需要使用selectKey这个好东西了。
首先来了解一下selectKey的j几个重要的属性:
keyProperty:Java对象的属性名
keyColumn:keyColumn是要和select语句中的表名相对应的实体类的字段对应的,但同时他也要和select语句中的列名对应
resultType:返回结果类型
order:返回查询前值(BEFORE)还是查询后的值(AFTER)
知道了selectKey的属性,我们还需要知道怎么获取到刚添加的记录的ID
MySQL有个函数:
敲黑板!!!
1、只适用于自增主键。
2、只对应insert语句
3、只会返回插入的第一行数据时产生的值(同时插入多行时)
参考文档:
MySQL :: MySQL 5.7参考手册:https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id
OK,此时我们就可以开始我们的搞事:
在一个insert中去实验一下
接口类中:
- /**
- * 保存方法
- * @param user
- */
- int saveUser(User user);
映射文件中:
- <insert id="saveUser" parameterType="com.moro.domain.User">
- <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
- select LAST_INSERT_ID();
- </selectKey>
- insert into user (username,birthday,sex) values (#{username},#{birthday},#{sex});
- </insert>
这样就可以获取到每次插入的记录的ID,问题来了,我们要怎么取出来呢?
写一个测试类try亿try
- private SqlSessionFactory sqlSessionFactory = null;
- private SqlSession sqlSession = null;
- private IUserDao iUserDao = null;
- private InputStream is = null;
- @Before
- public void init(){
- try {
- is = Resources.getResourceAsStream("SqlMapConfig.xml");
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (is != null) {
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
- sqlSession = sqlSessionFactory.openSession();
- iUserDao = sqlSession.getMapper(IUserDao.class);
- }
- }
- @Test
- public void testSave(){
-
- User user = new User("张三",new Date(),"男");
- iUserDao.saveUser(user);
-
- // 获取刚添加的ID
- System.out.println("刚添加的ID为:"+user.getId());
- // 提交事务
- sqlSession.commit();
- // 释放资源
- sqlSession.close();
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
执行OK!!!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。