MyBatis学习(三)- 小结

这里整理一下,使用MyBatis时遇到的一些问题:

1.主键

官方讲解:

首先,如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,而且设置 keyProperty 到你已经做好的目标属性上。例如,如果上面的 Author 表已经对 id 使用了自动生成的列类型,那么语句可以修改为:

[html]  view plain copy
  1. <insert id="insertAuthor" parameterType="domain.blog.Author" useGeneratedKeys="true"  
  2.     keyProperty="id">  
  3.   insert into Author (username,password,email,bio)  
  4.   values (#{username},#{password},#{email},#{bio})  
  5. </insert>  

MyBatis 有另外一种方法来处理数据库不支持自动生成类型,或者可能 JDBC 驱动不支持自动生成主键时的主键生成问题。

这里有一个简单(甚至很傻)的示例,它可以生成一个随机 ID(可能你不会这么做,但是这展示了 MyBatis 处理问题的灵活性,因为它并不真的关心 ID 的生成): 

[html]  view plain copy
  1. <insert id="insertAuthor" parameterType="domain.blog.Author">  
  2.   <selectKey keyProperty="id" resultType="int" order="BEFORE">  
  3.     select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1  
  4.   </selectKey>  
  5.   insert into Author  
  6.     (id, username, password, email,bio, favourite_section)  
  7.   values  
  8.     (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})  
  9. </insert>  

个人理解:在mapper.xml中,使用insert时,MySql和SqlServer都有主键自动增长的设置,我们可以这样配置

[html]  view plain copy
  1. <insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">  
  2.         <!-- 就是普通的插入语句,这里使用#{xxx}的方式赋值,这里的xxx要和实体类中的属性对应 -->  
  3.         insert into t_user(name , password , email , gender , age)  
  4.         values(#{name} , #{password} , #{email} , #{gender} , #{age})  
  5.     </insert>  

在Oracle中,自动增长的话,需要使用序列

[html]  view plain copy
  1. <insert id="insert" parameterType="User">  
  2.         <!-- 这里查询序列 -->  
  3.         <selectKey keyProperty="id" order="BEFORE" resultType="int">  
  4.             select s_demo_userId.nextval from dual  
  5.         </selectKey>  
  6.         insert into t_user(id , name , password , email , gender , age)  
  7.         values(#{id} , #{name} , #{password} , #{email} , #{gender} , #{age})  
  8.     </insert>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值