Mybatis第四篇:增删改

  主要包括增删改的返回值类型及主键获取方式

一、jdbc执行增删改默认返回int类型,Mybatis支持的返回值类型比jdbc强大,对于增删改具体支持如下返回类型:

int
Integer
long 
Long
boolean
Boolean
void

  如下为Mybatis增删改返回值的处理源码。

private Object rowCountResult(int rowCount) {
final Object result;
if (method.returnsVoid()) {
result = null;
} else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
result = rowCount;
} else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
result = (long)rowCount;
} else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
result = rowCount > 0;
} else {
throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
}
return result;
}

  Mybatis的返回值其实是对jdbc的int类型返回值的转换处理。

 二、Mybatis主键获取方式

  1、内部使用jdbc内置的方式:在XML文件的进行设置,往select的标签中增加useGeneratedKeys属性设置为true、设置keyProperty:参数对象中的属性名称,最后插入成功之后,mybatis会通过反射将自增值设置给keyProperty指定的这个属性。

  2、插入后查询获取主键:关键代码在于xml文件的sql的改写,主要是增加selectKey标签的那一部分代码,其中keyProperty配置的是bean对象中映射的字段,order配置为after意思是在insert插入之后操作。

  SELECT LAST_INSERT_ID():得到刚 insert 进去记录的主键值,只适用与自增主键

<insert id="insert" parameterType="entity.TUser">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into t_user (`name`, age, salary, 
      sex)
    values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=SMALLINT}, #{salary,jdbcType=DECIMAL}, 
      #{sex,jdbcType=TINYINT})
  </insert>

  3、插入前查询获取主键:xml的SQL语句与第二种情况相似,关键代码也是在selectKey这一部分的语句,其中的select部分需要换成自定义函数。不能用last_insert_id。

  last_insert_id只能用于拥有自增长主键的情况,插入前查询主键可以适用于不是自增长主键的情况,两者在高并发下存在问题。

原文地址:https://www.cnblogs.com/8593l/p/12705088.html