一 . MyBatis mapper.xml文件中在xml
1. 加入 这句 :useGeneratedKeys="true" keyProperty="ID"
keyProperty="数据库中的主键字段名对应的实体类字段名" ;【填实体类字段名】
<insert id="insertSelective" parameterType="com.tc.lvmsm.vo.vm.Vehicle"
useGeneratedKeys="true" keyProperty="ID">
2. 加 SELECT LAST_INSERT_ID()
<!-- 配置一个添加用户的sql语句,并且在查询之后得到用户的ID -->
<insert id="saveUser" parameterType="com.igeek.crm.pojo.User">
<!-- selectKey 标签实现主键返回 -->
<!-- keyColumn:主键对应的表中的哪一列 -->
<!-- keyProperty:主键对应的pojo中的哪一个属性 -->
<!-- order:设置在执行insert语句前执行查询id的sql,孩纸在执行insert语句之后执行查询id的sql -->
<!-- resultType:设置返回的id的类型 -->
<selectKey keyColumn="id" keyProperty="id" order="AFTER"
resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO `user`
(username,birthday,sex,address) VALUES
(#{username},#{birthday},#{sex},#{address})
</insert>
3.不适用自增ID ,使用UUID做主键 加 SELECT uuid()
<!-- 保存用户 使用UUID做主键 -->
<insert id="saveUser1" parameterType="com.igeek.crm.pojo.User">
<!-- selectKey 标签实现主键返回 -->
<!-- keyColumn:主键对应的表中的哪一列 -->
<!-- keyProperty:主键对应的pojo中的哪一个属性 -->
<!-- order:设置在执行insert语句前执行查询id的sql,在执行insert语句之后执行查询id的sql -->
<!-- resultType:设置返回的id的类型 -->
<selectKey keyColumn="uuid" keyProperty="uuid" order="BEFORE"
resultType="string">
SELECT uuid()
</selectKey>
INSERT INTO `user1`
(username,birthday,sex,address,uuid) VALUES
(#{username},#{birthday},#{sex},#{address},#{uuid})
</insert>
二.TkMyBatis通用Mapper中 在实体类的主键属性上加 注解:
1.自增主键用法:
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
2.序列主键用法(适用Oracle):
@Id
@GeneratedValue(
strategy = GenerationType.IDENTITY,
Generator = "select SEQ_ID.nextval from dual" )
private Integer id;
谢谢赞助与支持!