版权声明:本文为博主原创文章,未经博主允许不得转载。请联系博主或者emailTo:[email protected],谢谢! https://blog.csdn.net/caychen/article/details/80463486
首先添加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)、注解版
扫描二维码关注公众号,回复:
3663012 查看本文章
@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群: |
|
|