Mybatis通用mapper获得insert后的数据实体的自增ID

转自: https://blog.csdn.net/Appleyk/article/details/81360738

一、pom(基于Spring-Boot)

 


 
 
  1. <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter -->
  2. <dependency>
  3. <groupId>tk.mybatis </groupId>
  4. <artifactId>mapper-spring-boot-starter </artifactId>
  5. <version>1.1.5 </version>
  6. </dependency>

 

 

 

二、实体(xxxEntity)类中设置自增ID属性

 

 


 
 
  1. @Table(name = "${tablename}")
  2. public class XXXEntity {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. }

 

 

 

三、通用mapper

 

 


 
 
  1. import tk.mybatis.mapper.common.Mapper;
  2. public interface XXXMapper extends Mapper<XXXEntity> {
  3. /**
  4. * 什么都不用写,增删改查由底层的通用Mapper来为我们实现数据实体的增删改查
  5. * 如果需要写复杂SQL,需结合XML来配合通用mapper
  6. */
  7. }

 

 

 

四、demo(insert)测试

 

 


 
 
  1. int vID = XXXMapper.insert(XXXEntity);
  2. if(vID< 0){
  3. throw new BaseException(ResponseMessage.FAIL, "创建XXX失败");
  4. }
  5. System.out.println(XXXEntity.getId());

 

 

 

五、效果展示

 

 

 

 

 

六、自己写的Mapper实现主键自增

,对应的xml中应该设置useGeneratedKeys=“true”,keyProperty=相应的主键。

<insert id="inserContent" parameterType="userContent" useGeneratedKeys="true" keyProperty="id">
        insert into user_content(id, u_id, title, category, content, personal,rpt_time ,img_url,nick_name,upvote,downvote,comment_num) values(#{id}, #{uId},#{title}, #{category},#{content},#{personal},#{rptTime}, #{imgUrl},#{nickName},#{upvote},#{downvote},#{commentNum})
    </insert>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值