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

转自: https://blog.****.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());

 

 

 

五、效果展示

 

 

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

 

 

 

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

六、自己写的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>