====================mysql====================
MyBatis 3.2.6插入时候获取自增主键方法
以MySQL5.5为例:
方法1:
<insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
insert into person(name,pswd) values(#{name},#{pswd}) </insert>
方法2:
<insert id="insert" parameterType="Person">
<selectKey keyProperty="id" resultType="long"> select LAST_INSERT_ID() </selectKey> insert into person(name,pswd) values(#{name},#{pswd}) </insert>插入前实体id属性为0;
插入后实体id属性为保存后自增的id;
mysql、sqlserver等数据库本身带有主键自增长像auto_increment的功能可以直接使用
useGeneratedKeys=”true”来实现,比如下面的配置
insert into s_user_auth (id,user_id, user_name) values(#{id},#{userid},#{username})
==================oracle==========================
而oracle则不行,oracle主键自增长是通过sequence实现的,所以这种方式就不可以了,需要使用:
1.先通过sequence查出来id,再insert
select yoursequence.nextval as id from dual insert into s_user_auth (id,user_id, user_name) values(#{id},#{userid},#{username})
2.直接insertsequence.nextval,如下
insert into s_user_auth (id,user_id, user_name) values(yoursequence.nextval,#{userid},#{username})
3
<
insert
id
=
"save"
parameterType
="com.threeti.to.ZoneTO"
useGeneratedKeys=”false” >
<
selectKey
resultType
=
"java.lang.Long"
keyProperty
=
"id"
order
=
"AFTER"
>
SELECT SEQ_ZONE.CURRVAL AS id from dual
</
selectKey
>
insert into TBL_ZONE (ID, NAME
)
values (SEQ_ZONE.NEXTVAL, #{name,jdbcType=VARCHAR}
)
</
insert
>