Mapper中的使用
在insert中增加下面两个属性,useGeneratedKeys和keyProperty
useGeneratedKeys="true" keyProperty="id"
如果数据库支持自增主键,这样就可以了。如果不行,需要自己创建序列,然后通过序列获取主键值(使用的是postgresql中的函数,其他数据库视具体情况而定):
<insert id="insertValue" parameterType="map"
useGeneratedKeys="true" keyProperty="id">
<selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE">
SELECT nextval('sequence_name'::regclass) as id
</selectKey>
insert into table_name
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
...
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
...
</trim>
</insert>
当然你也可以这样使用
<insert id="insertValue" parameterType="map" useGeneratedKeys="true" keyProperty="id">
insert into table_name
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
...
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
(SELECT nextval('sequence_name'::regclass) as id),
</if>
...
</trim>
</insert>
这种使用方法也适用于批量执行插入的时候
<insert id="insertBatch" parameterType="java.util.List">
insert into table_name (
id,
...
) values
<foreach collection="list" item="item" index="index" separator=",">
((SELECT nextval('sequence_name'::regclass) as id),
...)
</foreach>
</insert>