mybatis免sql外掛之JpaMapper-以Jpa hibernate的風格寫mybatis(獲取spring容器中mybatis的mapper)
阿新 • • 發佈:2018-11-27
mybatis免sql外掛之JpaMapper-以Jpa hibernate的風格寫mybatis(獲取spring容器中mybatis的mapper)
簡介
JpaMapper以Jpa hibernate的風格寫mybatis的程式碼,可以減少手動寫sql的煩惱。
優勢:
- 不替換底層實現,僅生成sql並交給mybatis
- 方法基本與Jpa hibernate相似,易於框架替換,當然,沒那麼厲害,不支援聯表哦,專案還在繼續完善中。
- 提供簡單分表功能
- 邏輯簡單,可以拿去自己定製
gitee地址:https://gitee.com/xiaoyaofeiyang/JpaMapper
github地址:https://github.com/feiyangtianyao/jpa-mapper
本篇作為起始篇,先介紹一下如何從spring容器中獲取到mybatis的mapper/bean。
獲取mapper
spring環境下,可以使用
@Autowired
private List<SqlSessionFactory> sqlSessionFactoryList;
獲取到mybatis的SqlSessionFactory,SqlSessionFactory有你想要的一切mybatis配置。
比如mapper的class資訊:
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) { Configuration configuration = sqlSessionFactory.getConfiguration(); MapperRegistry mapperRegistry = configuration.getMapperRegistry(); List<Class<?>> mappers = new ArrayList<>(mapperRegistry.getMappers()); }
這樣就拿到了List<Class<?>> mappers。
定義自己的JPA風格的方法
Jpa hibernate最讓人喜歡的風格就是(個人認為):
- 繼承CrudRepository提供了最常用的一些方法。
- 使用findBy + 欄位即可實現查詢。這是所有mybatis的一些mapper工具都不具備的
- 名稱我喜歡
這裡,我們可以讓自己定義的mybatis的mapper繼承我們自己寫的CrudMapper,並定義與CrudRepository相似的方法。當然,mybatis不能有重複的方法名,因為它的MappedStatement是根據方法名唯一的。
其次,我們使用反射功能,讀取CrudMapper中的方法,根據我們的需求(這裡找到所有沒有加註解的方法)找到對應的方法,我們根據mybatis的生成MappedStatement的方法去生成對應的MappedStatement,並交給mybatis管理,這樣就可以實現我們想要的Jpa hibernate風格的dao層程式碼。
下篇介紹下如何生成MappedStatement。