您的位置:首页 > 编程语言 > Java开发

SpringBoot和Mybatis的整合

2018-07-30 14:52 260 查看

以前用Spring构建一个项目,配置文件太过麻烦而且很容易出错,而用SpringBoot,只需要填写必要的配置文件,可以很轻松整合Mybatis。下面开启SpringBoot之旅吧!

1、pom.xml引入相关依赖

[code]<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.jlu</groupId>
<artifactId>springboot_mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot_mybatis</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/>
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</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>
<scope>runtime</scope>
</dependency>
<!--引入druid-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

2、使用yaml配置文件比XML更加简洁明了。application.yml

[code]spring:
datasource:
#   数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.0.113:3306/mybatis
type: com.alibaba.druid.pool.DruidDataSource
#   数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#建表时用
#    schema:
#         - classpath:sql/department.sql
#         - classpath:sql/employee.sql

#-----以下是xml配置文件方式开发-------------
mybatis:
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml

如果想要自动建表,可在要第一次运行前将schema打开,建表sql放到指定路径下

3、实体类:Department(注解版测试用)和Employee(注解+XML配置版测试用)

[code]public class Department {

private Integer id;
private String departmentName;

//getters sttters toString...

}
[code]public class Employee {

private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;

//getters setters toString...
}

4、整合Druid数据源

[code]@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
initParams.put("allow", "");//默认就是允许所有访问
initParams.put("deny", "192.168.0.113");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}

5、实体类对应的Mapper

  DepartmentMapper:

[code]//@Mapper指定这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper {

@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);

@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);

//useGeneratedKeys:开启自增主键,keyProperty:Department中哪个属性与主键映射
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(department_name) values(#{departmentName})")
public int insertDept(Department department);

@Update("update department set department_name=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}

     EmplyeeMapper:

[code]//@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {

public Employee getEmpById(Integer id);

public void insertEmp(Employee employee);
}

注意mapper接口中如果不标明@Mapper,也可在主程序类里用@MapperScan注解扫描包

[code]//使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.jlu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {    
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);        
}    
}

 

第①方式:全注解版

1、编写controller:

[code]@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;

//根据id查询部门信息
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
//插入数据,并返回部门信息
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}

}

2、mapper接口

[code]//@Mapper指定这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper {

@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);

@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);

//useGeneratedKeys:开启自增主键,keyProperty:Department中哪个属性与主键映射
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(department_name) values(#{departmentName})")
public int insertDept(Department department);

@Update("update department set department_name=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}

 3、启动和测试:

访问http://localhost:8080/dept?departmentName=研发部(其中id是自增长,mapper中用@Options注解标明),向数据库插入一条数据

页面返回数据:{"id":1,"departmentName":"研发部"}

访问http://localhost:8080/dept/1,查询id为1的数据---{"id":1,"departmentName":"研发部"}

问题:

当实体类属性departmentName和表字段depaartment_name不一致时,访问http://localhost:8080/dept/1(返回的jsons数据{"id":1,"departmentName":NULL})。由于用全注解版,不能用XML配置开启驼峰命名规则,我们有2中办法解决这问题。

其一可以用@Results注解指定映射关系如下:

[code]    @Results({
@Result(property = "departmentName", column = "department_name")
})
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);

 其二我们可以编写一个自定义MyBatis的配置规则配置类;给容器中添加一个ConfigurationCustomizer;开启驼峰命名规则

(值得注意的是如果application.yml中引入了配置文件这个就没用了?)

[code]@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
//全局开启驼峰命名规则
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}

第②种方式:XML

1、controller

[code]@RestController
public class DeptController {

@Autowired
EmployeeMapper employeeMapper;

//数据插入略...
//根据id查询雇员信息
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}

}

2、mapper接口:

[code]//@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {

public Employee getEmpById(Integer id);

public void insertEmp(Employee employee);
}

3、SQL映射文件和mapper全局配置文件 

类路径下/mybaties/mapper/Employeemapper.xml

[code]<?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="com.jlu.springboot.mapper.EmployeeMapper">

<select id="getEmpById" resultType="com.jlu.springboot.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>

<insert id="insertEmp">
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>

类路径下/mybaties/mybatis-config.xml

[code]<?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>
<!--mybatis开启驼峰映射规则,数据库字段自动映射为实体类属性-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>

4、在application.yml在全局配置文件中

5、启动和测试

 访问http://localhost:8080/emp/1,查询id为1的数据

{"id":1,"lastName":"zhangSan",gender:0,email:"aaaa@163.com",dId:1}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: