近期需要搭建个基于spring4+mybatis3+mysql的框架.在搭建过程中遇到一些问题.现记录如下:
mysql的自增主键问题.
mapper有两种配置方式:
- 主键交由mysql自己生成: <insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="state != null">
STATE,
</if>
<if test="name != null">
NAME,
</if>
<if test="loginName != null">
LOGIN_NAME,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="state != null">
#{state,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="loginName != null">
#{loginName,jdbcType=VARCHAR},
</if>
</trim>
</insert> - 直接把主键写到配置文件中 <insert id="insert" parameterType="User" >
<selectKey keyProperty="id" resultType="int" order="BEFORE">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
ID,
<if test="state != null">
STATE,
</if>
<if test="name != null">
NAME,
</if>
<if test="loginName != null">
LOGIN_NAME,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
#{id},
<if test="state != null">
#{state,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="loginName != null">
#{loginName,jdbcType=VARCHAR},
</if>
</trim>
</insert>
当然,主键配置需要项目组根据情况自行配置,如果需要返回主键(针对多表关联插入)则需要第一种,第二种的会耗费一个查询主键的sql的性能