Mybatis通用Mapper介紹與使用
前言
使用Mybatis的開發者,大多數都會遇到一個問題,就是要寫大量的SQL在xml文件中,除了特殊的業務邏輯SQL之外,還有大量結構類似的增刪改查SQL。而且,當數據庫表結構改動時,對應的所有SQL以及實體類都需要更改。這工作量和效率的影響或許就是區別增刪改查程序員和真正程序員的屏障。這時,通用Mapper便應運而生……
什么是通用Mapper
通用Mapper就是為了解決單表增刪改查,基於Mybatis的插件。開發人員不需要編寫SQL,不需要在DAO中增加方法,只要寫好實體類,就能支持相應的增刪改查方法。
如何使用
以MySQL為例,假設存在這樣一張表:
1
2
3
4
5
6
7
8
9
10
|
CREATE
TABLE
`test_table` (
`id`
bigint
(20)
NOT
NULL
AUTO_INCREMENT,
`
name
`
varchar
(255)
DEFAULT
''
,
`create_time` datetime
DEFAULT
NULL
,
`create_user_id`
varchar
(32)
DEFAULT
NULL
,
`update_time` datetime
DEFAULT
NULL
,
`update_user_id`
varchar
(32)
DEFAULT
NULL
,
`is_delete`
int
(8)
DEFAULT
NULL
,
PRIMARY
KEY
(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1
DEFAULT
CHARSET=utf8;
|
主鍵是id
,自增。下面以這張表為例介紹如何使用通用Mapper。
Maven依賴
1
2
3
4
5
6
|
<!-- 通用Mapper -->
<
dependency
>
<
groupId
>tk.mybatis</
groupId
>
<
artifactId
>mapper</
artifactId
>
<
version
>3.3.9</
version
>
</
dependency
>
|
SpringMVC配置
1
2
3
4
5
6
7
8
9
|
<!-- 通用 Mapper -->
<
bean
class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<
property
name="basePackage" value="cn.com.bluemoon.bd.service.spider.dao"/>
<
property
name="properties">
<
value
>
mappers=tk.mybatis.mapper.common.Mapper
</
value
>
</
property
>
</
bean
>
|
注意這里使用tk.mybatis.spring.mapper.MapperScannerConfigure
替換原來Mybatis的org.mybatis.spring.mapper.MapperScannerConfigurer
。
1
2
3
4
5
6
7
8
9
10
11
|
可配參數介紹:
1.UUID:設置生成UUID的方法,需要用OGNL方式配置,不限制返回值,但是必須和字段類型匹配
2.IDENTITY:取回主鍵的方式,可以配置的內容看下一篇如何使用中的介紹
3.ORDER:<
seletKey
>中的order屬性,可選值為BEFORE和AFTER
4.catalog:數據庫的catalog,如果設置該值,查詢的時候表名會帶catalog設置的前綴
5.schema:同catalog,catalog優先級高於schema
6.seqFormat:序列的獲取規則,使用{num}格式化參數,默認值為{0}.nextval,針對Oracle,可選參數一共4個,對應0,1,2,3分別為SequenceName,ColumnName, PropertyName,TableName
7.notEmpty:insert和update中,是否判斷字符串類型!=’’,少數方法會用到
8style:實體和表轉換時的規則,默認駝峰轉下划線,可選值為normal用實體名和字段名;camelhump是默認值,駝峰轉下划線;uppercase轉換為大寫;lowercase轉換為小寫
9.enableMethodAnnotation:可以控制是否支持方法上的JPA注解,默認false。
大多數情況下不會用到這些參數,有特殊情況可以自行研究。
|
實體類的寫法
記住一個原則:實體類的字段數量 >= 數據庫表中需要操作的字段數量。默認情況下,實體類中的所有字段都會作為表中的字段來操作,如果有額外的字段,必須加上@Transient
注解。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
@Table(name = "test_table")
public class TestTableVO implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "JDBC")
private Long id;
@Transient
private String userId;
private String name;
private Timestamp createTime;
private String createUserId;
private Timestamp updateTime;
private String updateUserId;
private Integer isDelete;
// 省略get、set...
}
|
說明:
- 表名默認使用類名,駝峰轉下划線(只對大寫字母進行處理),如
UserInfo
默認對應的表名為user_info
。 - 表名可以使用
@Table(name = "tableName")
進行指定,對不符合第一條默認規則的可以通過這種方式指定表名. - 字段默認和
@Column
一樣,都會作為表字段,表字段默認為Java對象的Field名字駝峰轉下划線形式. - 可以使用
@Column(name = "fieldName")
指定不符合第3條規則的字段名 - 使用
@Transient
注解可以忽略字段,添加該注解的字段不會作為表字段使用. - 建議一定是有一個
@Id
注解作為主鍵的字段,可以有多個@Id
注解的字段作為聯合主鍵. - 如果是MySQL的自增字段,加上
@GeneratedValue(generator = "JDBC")
即可。如果是其他數據庫,可以參考官網文檔。
DAO
的寫法
在傳統的Mybatis寫法中,DAO
接口需要與Mapper
文件關聯,即需要編寫SQL
來實現DAO
接口中的方法。而在通用Mapper中,DAO
只需要繼承一個通用接口,即可擁有豐富的方法:
1
2
|
public
interface
TestTableDao
extends
Mapper<TestTableVO> {
}
|
繼承通用的Mapper,必須指定泛型
一旦繼承了Mapper,繼承的Mapper就擁有了Mapper所有的通用方法:
Select
方法:List<T> select(T record);
說明:根據實體中的屬性值進行查詢,查詢條件使用等號
方法:T selectByPrimaryKey(Object key);
說明:根據主鍵字段進行查詢,方法參數必須包含完整的主鍵屬性,查詢條件使用等號
方法:List<T> selectAll();
說明:查詢全部結果,select(null)方法能達到同樣的效果
方法:T selectOne(T record);
說明:根據實體中的屬性進行查詢,只能有一個返回值,有多個結果是拋出異常,查詢條件使用等號
方法:int selectCount(T record);
說明:根據實體中的屬性查詢總數,查詢條件使用等號
Insert
方法:int insert(T record);
說明:保存一個實體,null的屬性也會保存,不會使用數據庫默認值
方法:int insertSelective(T record);
說明:保存一個實體,null的屬性不會保存,會使用數據庫默認值
Update
方法:int updateByPrimaryKey(T record);
說明:根據主鍵更新實體全部字段,null值會被更新
方法:int updateByPrimaryKeySelective(T record);
說明:根據主鍵更新屬性不為null的值
Delete
方法:int delete(T record);
說明:根據實體屬性作為條件進行刪除,查詢條件使用等號
方法:int deleteByPrimaryKey(Object key);
說明:根據主鍵字段進行刪除,方法參數必須包含完整的主鍵屬性
Example方法
方法:List<T> selectByExample(Object example);
說明:根據Example條件進行查詢
重點:這個查詢支持通過Example
類指定查詢列,通過selectProperties
方法指定查詢列
方法:int selectCountByExample(Object example);
說明:根據Example條件進行查詢總數
方法:int updateByExample(@Param("record") T record, @Param("example") Object example);
說明:根據Example條件更新實體record
包含的全部屬性,null值會被更新
方法:int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
說明:根據Example條件更新實體record
包含的不是null的屬性值
方法:int deleteByExample(Object example);
說明:根據Example條件刪除數據
代碼中使用
在service
中注入dao
,即可使用
1
2
|
@Autowired
private
TestTableDao testTableDao;
|
新增
1
2
3
|
TestTableVO vo =
new
TestTableVO();
// 省略為vo設置屬性...
int
row = testTableDao.insertSelective(vo);
|
修改
1
2
3
|
TestTableVO vo =
new
TestTableVO();
// 省略為vo設置屬性...
int
row = testTableDao.updateByPrimaryKeySelective(vo);
|
查詢單個
1
2
3
|
TestTableVO vo =
new
TestTableVO();
vo.setId(123L);
TestTableVO result = testTableDao.selectOne(vo);
|
條件查詢
1
2
3
4
5
6
7
8
|
// 創建Example
Example example =
new
Example(TestTableVO.
class
);
// 創建Criteria
Example.Criteria criteria = example.createCriteria();
// 添加條件
criteria.andEqualTo(
"isDelete"
,
0
);
criteria.andLike(
"name"
,
"%abc123%"
);
List<TestTableVO> list = testTableDao.selectByExample(example);
|
總結
通用Mapper的原理是通過反射獲取實體類的信息,構造出相應的SQL,因此我們只需要維護好實體類即可,對於應付復雜多變的需求提供了很大的便利。上文敘述的只是通用Mapper的簡單用法,在實際項目中,還是要根據業務,在通用Mapper的基礎上封裝出粒度更大、更通用、更好用的方法。
附 Spring Boot 配置
1
2
3
4
5
6
7
8
9
10
11
12
|
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>
1.3
.
1
</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>
1.1
.
4
</version>
</dependency>
|
1
2
3
4
5
|
#mapper
#mappers 多個接口時逗號隔開
mapper.mappers=tk.mybatis.mapper.common.Mapper
mapper.not-empty=
false
mapper.identity=MYSQL
|
Example舉例:
1
2
3
4
5
6
7
8
9
10
11
|
public
List<TestTableVO> getByExample(String name) {
//查詢器
Example example =
new
Example(TestTableVO.
class
);
//獲得criteria
Example.Criteria criteria=example.createCriteria();
//參數為 屬性名+值
criteria.andEqualTo(
"name"
,name);
//排序
example.orderBy(
"age"
).desc();
return
testTableDao.selectByExample(example);
}
|
模糊查詢:
1
2
3
4
5
6
7
8
9
10
11
|
public
List<TestTableVO> getByExampleAndKey(String key) {
//查詢器
Example example =
new
Example(TestTableVO.
class
);
Example.Criteria criteria=example.createCriteria();
/**
* 第一個參數是key:值得屬性
* 第二個是值:指匹配的值
*/
criteria.andLike(
"name"
,
"%"
+ key +
"%"
);
return
testTableDao.selectByExample(example);
}
|