使用Mybatis的開發者,大多數都會遇到一個問題,就是要寫大量的SQL在xml文件中,除了特殊的業務邏輯SQL之外,還有大量結構類似的增刪改查SQL。而且,當數據庫表結構改動時,對應的所有SQL以及實體類都需要更改。這工作量和效率的影響或許就是區別增刪改查程序員和真正程序員的屏障。這時,通用Mapper便應運而生……
什么是通用Mapper
通用Mapper就是為了解決單表增刪改查,基于Mybatis的插件。開發人員不需要編寫SQL,不需要在DAO中增加方法,只要寫好實體類,就能支持相應的增刪改查方法。
如何使用
以MySQL為例,假設存在這樣一張表:
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依賴
<!-- 通用Mapper --><dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.3.9</version></dependency>
SpringMVC配置
<!-- 通用 Mapper --><beanclass="tk.mybatis.spring.mapper.MapperScannerConfigurer"> <propertyname="basePackage"value="cn.com.bluemoon.bd.service.spider.dao"/> <propertyname="properties"> <value> mappers=tk.mybatis.mapper.common.Mapper </value> </property></bean>
注意這里使用 tk.mybatis.spring.mapper.MapperScannerConfigure
替換原來Mybatis的 org.mybatis.spring.mapper.MapperScannerConfigurer
。
可配參數介紹:
大多數情況下不會用到這些參數,有特殊情況可以自行研究。
實體類的寫法
記住一個原則:實體類的字段數量 >= 數據庫表中需要操作的字段數量。默認情況下,實體類中的所有字段都會作為表中的字段來操作,如果有額外的字段,必須加上 @Transient
注解。
@Table(name = "test_table")public class TestTableVOimplements 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... }
說明:
DAO 的寫法
在傳統的Mybatis寫法中, DAO 接口需要與 Mapper 文件關聯,即需要編寫 SQL 來實現 DAO 接口中的方法。而在通用Mapper中, DAO 只需要繼承一個通用接口,即可擁有豐富的方法:
繼承通用的Mapper ,必須指定泛型
public interface TestTableDaoextends Mapper<TestTableVO>{}
一旦繼承了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 ,即可使用。
@Autowiredprivate TestTableDao testTableDao;
下面演示大概的寫法:
新增
TestTableVO vo = new TestTableVO();// 省略為vo設置屬性...int row = testTableDao.insertSelective(vo);
修改
TestTableVO vo = new TestTableVO();// 省略為vo設置屬性...int row = testTableDao.updateByPrimaryKeySelective(vo);
查詢單個
TestTableVO vo = new TestTableVO();vo.setId(123L);TestTableVO result = testTableDao.selectOne(vo);
條件查詢
// 創建ExampleExample example = new Example(TestTableVO.class);// 創建CriteriaExample.Criteria criteria = example.createCriteria();// 添加條件criteria.andEqualTo("isDelete", 0);criteria.andLike("name", "%abc123%");List<TestTableVO> list = testTableDao.selectByExample(example);
總結
通用Mapper的原理是通過反射獲取實體類的信息,構造出相應的SQL,因此我們只需要維護好實體類即可,對于應付復雜多變的需求提供了很大的便利。上文敘述的只是通用Mapper的簡單用法,在實際項目中,還是要根據業務,在通用Mapper的基礎上封裝出粒度更大、更通用、更好用的方法。
附 Spring Boot 配置
Maven
<!--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>
application.properties 配置
#mapper#mappers 多個接口時逗號隔開mapper.mappers=tk.mybatis.mapper.common.Mappermapper.not-empty=falsemapper.identity=MYSQL
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選