mybatis+oracle 完成插入數據庫,並將主鍵返回的注意事項
一條插入語句就踩了不少的坑,
首先我的建表語句是:
create table t_openapi_batch_info(
BATCH_NO VARCHAR2(200),
UM_CODE VARCHAR2(50),
BATCH_STATUS CHAR(1) DEFAULT '0',
BATCH_TYPE CHAR(1),
CREATED_DATE DATE,
CREATED_BY VARCHAR(100),
UPDATED_DATE DATE
UPDATED_BY VARCHAR(100)
)
CREATE SEQUENCE SEQ_OPENAPI_BATCHNO
minvalue 0
maxvalue 999999999
start wuth 7342937
increate by 1
cache 40;
我寫的mapper.xml的sql語句爲:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper>
<insert id="insertBatchInfo" parameterType="java.util.Map" useGeneratedKeys="true" keyColumn ="batchNo">
<selectKey resultType="int" keyProperty="batchNo" order="BEFORE">
select seq_openapi_batchno.nextval as batchNo from dual
</selectKey>
insert into t_openapi_batch_info
<include refid="batchInfoKey"/>
VALUES
<include refid="batchInfoVal"/>
</insert>
<sql id="batchInfoKey">
<trim prefix="(" suffix=")">
batch_no,
<if test="umCode!=null and umCode!=''">
um_code,
</if>
<if test="batchStatus!=null and batchStatus!=''">
batch_status,
</if>
<if test="batchType!=null and batchType!=''">
batch_type,
</if>
created_by,created_date,updated_by,updated_date
</trim>
</sql>
<sql id="batchInfoVal">
<trim prefix="(" suffix=")">
#{batchNo},
<if test="umCode!=null and umCode!=''">
#{umCode},
</if>
<if test="batchStatus!=null and batchStatus!=''">
#{batchStatus},
</if>
<if test="batchType!=null and batchType!=''">
#{batchType},
</if>
user,sysdate,user,sysdate
</trim>
</sql>
</mapper>
截取上面mapper文件中的重要的部分,
1.使用useGeneratedkey,默認爲false,設置爲true可以將需要的值返回
2.keyColumn這個值可以指定你需要返回的值,比如我需要返回批次號,那麼就可以指定keyColumn的值爲batchNo,此時我可以將batchNo綁定到map,當然,如果你的參數類型是dto的話,就會綁定到對應實體類的屬性上面,使用map.get(“batchNo”)就可以得到相應的值。
3.resultType=“int”,這裏我踩得坑是將resultType寫成了String類型**
/**
* 這個方法是對SqlSession的包裝,對應insert、delete、update、select四種操作
*/
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;//返回結果
//INSERT操作
if (SqlCommandType.INSERT == command.getType()) {
//處理參數
Object param = method.convertArgsToSqlCommandParam(args);
//調用sqlSession的insert方法
result = rowCountResult(sqlSession.insert(command.getName(), param));
} else if (SqlCommandType.UPDATE == command.getType()) {
//UPDATE操作 同上
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
} else if (SqlCommandType.DELETE == command.getType()) {
//DELETE操作 同上
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
} else if (SqlCommandType.SELECT == command.getType()) {
//如果返回void 並且參數有resultHandler ,則調用 void select(String statement, Object parameter, ResultHandler handler);方法
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
//如果返回多行結果,executeForMany這個方法調用 <E> List<E> selectList(String statement, Object parameter);
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
//如果返回類型是MAP 則調用executeForMap方法
result = executeForMap(sqlSession, args);
} else {
//否則就是查詢單個對象
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
} else {
//接口方法沒有和sql命令綁定
throw new BindingException("Unknown execution method for: " + command.getName());
}
//如果返回值爲空 並且方法返回值類型是基礎類型 並且不是VOID 則拋出異常
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
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;
}
所以通過源碼我們可以知道insert ,update,delete操作只能返回int,lang,boolean類型,若返回string類型,就會報錯。
4.keyProperty 是 selectKey 語句結果應該被設置的目標屬性。
SelectKey需要注意order屬性,像Mysql一類支持自動增長類型的數據庫中,order需要設置爲after纔會取到正確的值。
像Oracle這樣取序列的情況,需要設置爲before
,否則會報錯。