關於MyBatis,大部分人都很熟悉。MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎全部的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。java
無論是DDD(Domain Driven Design,領域驅動建模)仍是分層架構的風格,都會涉及到對數據庫持久層的操做,本文將會講解Spring Boot集成MyBatis如何實現通用Mapper。mysql
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
複製代碼
能夠看到如上關於Mybatis引入了mybatis-spring-boot-starter
,由Mybatis提供的starter。git
在application.yml中增長以下配置:github
spring:
datasource:
hikari:
connection-test-query: SELECT 1
minimum-idle: 1
maximum-pool-size: 5
pool-name: dbcp1
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf-8
username: user
password: pwd
type: com.zaxxer.hikari.HikariDataSource
schema[0]: classpath:/init.sql
initialize: true
複製代碼
能夠看到,咱們配置了hikari和數據庫的基本信息。在應用服務啓動時,會自動初始化classpath下的sql腳本。web
CREATE TABLE IF NOT EXISTS `test` (
`id` bigint(20) unsigned NOT NULL,
`local_name` varchar(128) NOT NULL ,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
複製代碼
在sql腳本中,咱們建立了一張test
表。spring
到這裏,後面咱們通常須要配置Mybatis映射的xml文件和實體類的路徑。根據mybatis generator 自動生成代碼。包括XXMapper.java
,XXEntity.java
, XXMapper.xml
。這裏咱們就不演示了,直接進入下一步的通用Mapper實現。sql
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.0</version>
</dependency>
複製代碼
通用Mapper的做者abel533,有興趣可閱讀源碼。數據庫
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import java.util.Properties;
@Configuration
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.blueskykong.mybatis.dao");//掃描該路徑下的dao
Properties properties = new Properties();
properties.setProperty("mappers", "com.blueskykong.mybatis.config.BaseDao");//通用dao
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
複製代碼
在配置中,設定了指定路徑下的dao,並指定了通用dao。須要注意的是,MapperScannerConfigurer
來自於tk.mybatis.spring.mapper
包下。bash
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface BaseDao<T> extends Mapper<T>,MySqlMapper<T>{
}
複製代碼
通用Mapper接口,其餘接口繼承該接口便可。微信
咱們須要添加test
表對應的實體。
@Data
@Table(name = "test")
@AllArgsConstructor
@NoArgsConstructor
public class TestModel {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String localName;
}
複製代碼
其中,@Table(name = "test")
註解指定了該實體對應的數據庫表名。
mybatis:
configuration:
map-underscore-to-camel-case: true
複製代碼
爲了更好地映射Java實體和數據庫字段,咱們指定下劃線駝峯法的映射配置。
public interface TestDao extends BaseDao<TestModel> {
@Insert("insert into test(id, local_name) values(#{id}, #{localName})")
Integer insertTestModel(TestModel testModel);
}
複製代碼
TestDao
繼承自BaseDao
,並指定了泛型爲對應的TestModel
。TestDao
包含繼承的方法,如:
int deleteByPrimaryKey(Integer userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
複製代碼
還能夠自定義一些方法,咱們在上面自定義了一個insertTestModel
方法。
本文略過這兩層,比較簡單,讀者能夠參見本文對應的源碼地址。
咱們在插入一條數據以後,查詢對應的實體。對應執行的結果也都是成功,能夠看到控制檯的以下日誌信息:
c.b.mybatis.dao.TestDao.insertTestModel : ==> Preparing: insert into test(id, local_name) values(?, ?)
c.b.mybatis.dao.TestDao.insertTestModel : ==> Parameters: 5953(Integer), testName(String)
c.b.mybatis.dao.TestDao.insertTestModel : <== Updates: 1
c.b.m.dao.TestDao.selectByPrimaryKey : ==> Preparing: SELECT id,local_name FROM test WHERE id = ?
c.b.m.dao.TestDao.selectByPrimaryKey : ==> Parameters: 5953(Integer)
c.b.m.dao.TestDao.selectByPrimaryKey : <== Total: 1
複製代碼
Spring Boot集成MyBatis實現通用Mapper到此就大功告成。
MyBatis是持久層很是經常使用的組件,Spring Boot倡導約定優於配置,特別是不少xml的配置。固然還有不少同窗使用Spring Data。相比而言,我以爲MyBatis的SQL比Spring Data更加靈活,至於具體比較不在此討論。
本文對應的源碼地址:
github.com/keets2012/S…