您当前的位置: 首页 >  mybatis

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【精品】MyBatis返回增数据主键的值

梁云亮 发布时间:2022-09-20 11:26:19 ,浏览量:2

假设数据库表中有一个bigint+autoincremnt类型的字段id,在采用MyBatis技术往表中添加数据时,可以通过以下几种方式获取新增记录的主键值。

方式一
  • 单个插入

	INSERT INTO tb_user (username,password)
 	VALUES (#{username},#{password})

  • 批量插入

  insert into tb_user(username, password) 
  values
  
    (#{item.username}, #{item.password}
  

方式二

    
      select LAST_INSERT_ID()
    
    insert into tb_user(username, password) 
    values  
     (#{username},#{password})
  

其实对于这种方式来说,也可以返回非自增方式新增记录主键的值


    
		  select uuid() as id
	
    insert into tb_user(username, password) values (#{username},#{password})
  
方式三
@Insert("insert into tb_user(username, password) values (#{username},#{password})")
@SelectKey(statement = "select last_insert_id()",keyProperty = "id",before = false,resultType = Long.class)
int insert(Province province);
方式四
@InsertProvider(type =MapperProvider.class, method = "insert")
@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
//@Options和@SelectKey都能够实现功能:返回新增记录的自增长主键id字段值
//@SelectKey(statement = "select last_insert_id()",keyProperty = "id",before = false,resultType = Long.class)
int insert(User user);

其中 public class MapperProvider{ public String insert(User user) { return “insert into tb_user(username, password) values (”+user.getName+“,”+user.getPassword+“)” } }

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0396s