这里整理一下,使用MyBatis时遇到的一些问题:
1.主键
官方讲解:
首先,如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,而且设置 keyProperty 到你已经做好的目标属性上。例如,如果上面的 Author 表已经对 id 使用了自动生成的列类型,那么语句可以修改为:
<insert id="insertAuthor" parameterType="domain.blog.Author" useGeneratedKeys="true"
keyProperty="id">
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
MyBatis 有另外一种方法来处理数据库不支持自动生成类型,或者可能 JDBC 驱动不支持自动生成主键时的主键生成问题。
这里有一个简单(甚至很傻)的示例,它可以生成一个随机 ID(可能你不会这么做,但是这展示了 MyBatis 处理问题的灵活性,因为它并不真的关心 ID 的生成):
<insert id="insertAuthor" parameterType="domain.blog.Author">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
个人理解:在mapper.xml中,使用insert时,MySql和SqlServer都有主键自动增长的设置,我们可以这样配置
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
<!-- 就是普通的插入语句,这里使用#{xxx}的方式赋值,这里的xxx要和实体类中的属性对应 -->
insert into t_user(name , password , email , gender , age)
values(#{name} , #{password} , #{email} , #{gender} , #{age})
</insert>
在Oracle中,自动增长的话,需要使用序列
<insert id="insert" parameterType="User">
<!-- 这里查询序列 -->
<selectKey keyProperty="id" order="BEFORE" resultType="int">
select s_demo_userId.nextval from dual
</selectKey>
insert into t_user(id , name , password , email , gender , age)
values(#{id} , #{name} , #{password} , #{email} , #{gender} , #{age})
</insert>