MyBatis 主鍵返回策略
最近在項目中需要用到MyBatis的主鍵返回策略,感覺官方文檔給的例子很簡短,上網搜索時又被人所誤導,可能也是自己沒認真看官方文檔,特此記錄。
背景
- Mysql 數據庫
- 表主鍵自增(注意當表主鍵已設置自增時使用下面實現,MyBatis存在兩種實現)
先把實現展示下
實現
這個是我最終的實現,其實很簡單。
Mapper接口
@Mapper
public interface TagMapper extends BaseMapper<Tag> {
Integer insertTag(Tag tag);
}
xml配置
<insert id="insertTag" useGeneratedKeys="true" keyProperty="id" parameterType="com.fxtahe.blog.entity.Tag">
INSERT INTO tag (tag_name) VALUES (#{tagName})
</insert>
接口調用
@Test
public void testInsertTag(){
Tag tag = new Tag();
tag.setTagName("標籤");
tagMapper.insertTag(tag);
// 參數中獲取主鍵id
Integer id = tag.getId();
}
總結
下面記錄下我犯的比較蠢的問題,也是對MyBatis不夠了解導致
注意:
- 1.接口入參必須爲實體類
- 2.接口返回的Integer是插入的行數,並不是返回的主鍵
看下官網的介紹
如果你的數據庫支持自動生成主鍵的字段(比如 MySQL 和 SQL Server),那麼你可以設置 useGeneratedKeys=”true”,然後再把 keyProperty 設置到目標屬性上就 OK 了
xml配置的keyProperty
是將返回的主鍵設置到入參的實體類中,所以傳參爲實體類。
selectKey
Mybatis也提供了另一種主鍵返回的方式,主要是應對不支持自增主鍵的,把MyBatis官網的內容貼過來
對於不支持自動生成類型的數據庫或可能不支持自動生成主鍵的 JDBC 驅動,MyBatis 有另外一種方法來生成主鍵。
這裏有一個簡單(甚至很傻)的示例,它可以生成一個隨機 ID(你最好不要這麼做,但這裏展示了 MyBatis 處理問題的靈活性及其所關心的廣度):
<insert id="insertAuthor">
<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>
參考: MyBatis官網