【Spring Boot】(23)、Spring Boot整合Mybatis
阿新 • • 發佈:2018-10-31
首先新增mybatis依賴:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
1)、新增資料來源依賴及連線池
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
spring: datasource: url: jdbc:mysql:///springboot username: root password: admin type: com.alibaba.druid.pool.DruidDataSource initialSize: 5 minIdle: 5 maxActive: 20 schema: - classpath*:sql/department.sql - classpath*:sql/employee.sql
4)、註解版
@Mapper public interface DepartmentMapper { @Select("select * from department where id = #{id}") public Department getById(Integer id); @Delete("delete from department where id = #{id}") public int deleteById(Integer id); @Insert("insert into department(departmentName) values(#{departmentName})") @Options(useGeneratedKeys = true, keyProperty = "id") public int insert(Department department); @Update("update department set departmentName = #{departmentName} where id = #{id}") public int update(Department department); }
問題1:如果資料庫欄位與實體屬性的不能匹配,但是資料庫欄位使用下劃線來區分隔開,而實體類屬性使用駝峰法命名,這樣的欄位如何使用註解版的mybatis來解決呢?
解決方法1:定義一個mybatis的配置類,並配置一個ConfigurationCustomizer型別的Bean,並將駝峰命名規則設為true即可。
@Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return configuration -> {
configuration.setMapUnderscoreToCamelCase(true);
};
}
}
MybatisAutoConfiguration自動配置類中,建立了一個SqlSessionFactory的Bean:
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {
factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
Configuration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
configuration = new Configuration();
}
//獲取所有的Mybatis中的ConfigurationCustomizer定製器,執行各自的定製方法
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
customizer.customize(configuration);
}
}
factory.setConfiguration(configuration);
if (this.properties.getConfigurationProperties() != null) {
factory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
if (!ObjectUtils.isEmpty(this.interceptors)) {
factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {
factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
factory.setMapperLocations(this.properties.resolveMapperLocations());
}
return factory.getObject();
}
SqlSessionFactory的Bean的時候,會依次呼叫每個Mybatis定製器的customize定製方法,從而修改mybatis的預設配置。
所以可以自定義一個Mybatis的ConfigurationCustomizer定製器即可。
解決方法2:在全域性配置檔案中新增配置:
# 開啟駝峰命名法規則
mybatis.configuration.map-underscore-to-camel-case=true
解決方法:使用@Results註解,用於定義之前mybatis的xml對映檔案中的<resultMap />標籤:
@Mapper
public interface DepartmentMapper {
@Results({
@Result(column = "id", property = "id", id = true),
@Result(column = "department_name", property = "departmentName")
})
@Select("select * from department where id = #{id}")
public Department getById(Integer id);
@Delete("delete from department where id = #{id}")
public int deleteById(Integer id);
@Insert("insert into department(department_name) values(#{departmentName})")
@Options(useGeneratedKeys = true, keyProperty = "id")
public int insert(Department department);
@Update("update department set department_name = #{departmentName} where id = #{id}")
public int update(Department department);
}
@Mapper註解會比較麻煩,是否有更簡便的方法來配置介面呢?
解決方法:(通常)在主程式入口上新增@MapperScan註解,用於指定掃描mapper介面的包路徑:
@MapperScan(basePackages = "mapper介面所在的包路徑")
@MapperScan(basePackages = {"包1", "包2", "包3"})
首先編寫一個mybatis全域性配置檔案(如果不需要任何配置,則不需要該檔案配置):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
public interface EmployeeMapper {
public Employee getById(Integer id);
public Employee insert(Employee employee);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.com.cay.spring.boot.dao.EmployeeMapper">
<select id="getById" resultType="employee">
SELECT * FROM employee
<where>
id = #{id}
</where>
</select>
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO employee(lastName, email, gender, d_id)
VALUES
(
#{lastName},
#{email},
#{gender},
#{dId}
)
</insert>
</mapper>
mybatis:
# 如果無需設定,則可以忽略mybatis.config-location
# config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: org.com.cay.spring.boot.entity
====================打個廣告,歡迎關注====================
QQ: |
412425870 |
微信公眾號:Cay課堂 |
|
csdn部落格: |
http://blog.csdn.net/caychen |
碼雲: |
https://gitee.com/caychen/ |
github: |
https://github.com/caychen |
點選群號或者掃描二維碼即可加入QQ群: |
|
|