Mybatis通用mapper获得insert后的数据实体的自增ID
转自: https://blog.****.net/Appleyk/article/details/81360738
-
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter -->
-
<dependency>
-
<groupId>tk.mybatis</groupId>
-
<artifactId>mapper-spring-boot-starter</artifactId>
-
<version>1.1.5</version>
-
</dependency>
二、实体(xxxEntity)类中设置自增ID属性
-
@Table(name = "${tablename}")
-
public class XXXEntity {
-
-
@Id
-
@GeneratedValue(strategy = GenerationType.IDENTITY)
-
private Long id;
-
}
三、通用mapper
-
import tk.mybatis.mapper.common.Mapper;
-
-
public interface XXXMapper extends Mapper<XXXEntity> {
-
/**
-
* 什么都不用写,增删改查由底层的通用Mapper来为我们实现数据实体的增删改查
-
* 如果需要写复杂SQL,需结合XML来配合通用mapper
-
*/
-
}
四、demo(insert)测试
-
int vID = XXXMapper.insert(XXXEntity);
-
if(vID<0){
-
throw new BaseException(ResponseMessage.FAIL,"创建XXX失败");
-
}
-
-
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>