在使用MyBatis做持久層時,insert語句默認是不返回記錄的主鍵值,而是返回插入的記錄條數;
Dao.java
@Override public int insert(T record) { for (DaoInsertInterceptor<T> interceptor : this.insertInterceptors) { interceptor.invoke(this, record); } return super.getSqlSession().insert(this.mapperNamespace + ".insert", record); }
如果業務層需要得到記錄的主鍵時,可以通過配置的方式來完成這個功能
EventService.java
@Override @Transactional public int insert(Event event) { this.eventDao.insert(event); return event.getEventId(); }
針對Sequence主鍵而言,在執行insert sql前必須指定一個主鍵值給要插入的記錄,如Oracle、DB2,可以采用如下配置方式:
<insert id="insert" parameterType="cn.com.bmsoft.smartcity.govnet.domain.Evenlegal"> <selectKey keyProperty="legalId" resultType="int" order="BEFORE"> select GOVNET_SEQ.nextVal from dual </selectKey> insert into T_GOVNET_EVENT_LEGAL ( "LEGAL_ID", "LEGAL_DESC", "SORTORDER" ) values ( #{legalId,jdbcType=INTEGER}, #{legalDesc,jdbcType=VARCHAR}, #{sortorder,jdbcType=INTEGER} ) </insert>
針對自增主鍵的表,在插入時不需要主鍵,而是在插入過程自動獲取一個自增的主鍵,比如mysql、sqlserver,可以采用如下兩種配置方式:
useGeneratedKeys
取值范圍true|false
默認值是:false。
含義:設置是否使用JDBC的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設置的領域模型屬性中。MySQL和SQLServer執行auto-generated key field,因此當數據庫設置好自增長主鍵后,可通過JDBC的getGeneratedKeys方法獲取。但像Oralce等不支持auto-generated key field的數據庫就不能用這種方法獲取主鍵了
<insert id="insert" parameterType="cn.com.bmsoft.base.domain.management.FileManageTree" useGeneratedKeys="true" keyProperty="eventId"> insert into T_FILE_MANAGE_TREE ( CODE, NAME ) values ( #{code,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR} ) </insert>
或
<insert id="insert" parameterType="cn.com.bmsoft.smartcity.govnet.domain.Evenlegal"> <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() AS id </selectKey> insert into T_GOVNET_EVENT_LEGAL ( "LEGAL_ID", "LEGAL_DESC", "SORTORDER" ) values ( #{legalId,jdbcType=INTEGER}, #{legalDesc,jdbcType=VARCHAR}, #{sortorder,jdbcType=INTEGER} ) </insert>
