对于支持生成自增主键的数据库:useGenerateKeys和keyProperty
不支持生成自增主键的数据库:<selectKey>
mysql:
我们需要 刚才插入的主键(主键来自序列) useGeneratedKeys="true" //要使用主键 并赋值到 keyProperty指定的属性中 keyProperty="id" 要把主键给哪个字段 java类中的属性字段 keyColumn="ID" 数据库中自动生成的主键名 返回的主键会自动设置到实体类 对应的id属性中
下面正常写代码
<insert id="insertSelective" parameterType="com.gs.pojo.User1" useGeneratedKeys="true" keyProperty="id" keyColumn="ID" >
oracle:
我的序列:
-- Create sequence
create sequence USER_SEQ
minvalue 1
maxvalue 9999999999999999999999999999
start with 100
increment by 1
cache 20;
不支持生成自增主键的数据库:<selectKey>
<insert id="insertSelective" parameterType="com.gs.pojo.User1" >
<selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="id">
select USER_SEQ.NEXTVAL from DUAL
</selectKey>
insert into USER1
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
ID,
</if>
<if test="email != null" >
EMAIL,
</if>
<if test="password != null" >
PASSWORD,
</if>
<if test="truename != null" >
TRUENAME,
</if>
<if test="gender != null" >
GENDER,
</if>
<if test="phone != null" >
PHONE,
</if>
<if test="deptId != null" >
DEPT_ID,
</if>
<if test="isValid != null" >
IS_VALID,
</if>
<if test="createTime != null" >
CREATE_TIME,
</if>
<if test="updateTime != null" >
UPDATE_TIME,
</if>
<if test="iconUrl != null" >
ICON_URL,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=VARCHAR},
</if>
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="truename != null" >
#{truename,jdbcType=VARCHAR},
</if>
<if test="gender != null" >
#{gender,jdbcType=VARCHAR},
</if>
<if test="phone != null" >
#{phone,jdbcType=VARCHAR},
</if>
<if test="deptId != null" >
#{deptId,jdbcType=DECIMAL},
</if>
<if test="isValid != null" >
#{isValid,jdbcType=VARCHAR},
</if>
<if test="createTime != null" >
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null" >
#{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="iconUrl != null" >
#{iconUrl,jdbcType=VARCHAR},
</if>
</trim>
</insert>
会把序列值塞到id里
java代码取值:
private void relationUser_role(Long id, String roleIds) {
System.out.println("获取到的级联添加id是:" +id);
}
控制台结果: