上篇文章我们使用SpringBoot搭建了一个web项目,并在页面展示效果(SpringMvc),现在我们使用springBoot整合Mybatis,当然不能少了mysql。
一、springBoot整合Mybatis
创建springBoot项目时,继承springBoot父类中的mybatis和mysql
或者是在项目中直接添加依赖的jar包
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--alibaba druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.13</version>
</dependency>
二、添加配置文件
这里我们摒弃项目默认提供的application.properties文件,使用application.yml文件,为什么不使用官方默认提供的properties文件?原因有很多,在这里我就说一个最重要的:不好看!!!!!!
创建两个yml文件,分别是:application.yml,application-dev.yml
application.yml
spring:
profiles:
active: dev
application-dev.yml
server:
port: 8080
spring:
datasource:
username: yancy
password: yancy
url: jdbc:mysql://127.0.0.1:3306/yan_1808
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource #druid连接池
dbcp2:
initial-size: 5 #初始化提供的连接数
min-idle: 5 # 数据库连接池的最小维持连接数
max-idle: 5 # 最大的连接数
mybatis:
#config-location: classpath:mybatis/mybatis-config.xml #引入mybatis-config.xml文件
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: com.yan.entity #aliases别名
configuration: #开启驼峰命名
map-underscore-to-camel-case: true
logging: #显示sql语句
level:
com:
yan:
mapper : debug
在Spring Boot中多环境配置文件名需要满足application-{profile}.yml的格式,其中{profile}对应你的环境标识
application-dev.yml:开发环境
application-test.yml:测试环境
application-prod.yml:生产环境
需要在application.yml文件中通过spring.profiles.active属性来设置需要被加载的yml文件
三、测试springBoot整合mybatis
controller
/**
* Created by yan on 2019/2/7.
*/
@Controller
public class Usercontroller {
@Autowired
private IUserService userService;
@RequestMapping("user/{id}")
@ResponseBody
public User userList(@PathVariable("id") int id){
return userService.selectUserById(id);
}
}
service
/**
* Created by yan on 2019/2/7.
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectUserById(int id) {
return userMapper.selectUserById(id);
}
}
mapper
<?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.yan.mapper.UserMapper">
<select id="selectUserById" resultType="user">
select * from t_user where us_id = #{usId}
</select>
</mapper>
四、springBoot事务
在启动类上添加
@EnableTransactionManagement
在serviceimpl(业务逻辑类)上添加
@Transactional
五、mapper.xml文件存放位置
在idea中xml文件默认存放在resources中才可以被读取,但是我们习惯于存放在java目录下
在pom文件中的build标签中添加
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
同时在application-dev.yml中将以下内容注释掉
mapper-locations: classpath:mapping/*Mapper.xml
六、注意事项
mapper接口只有添加@mapper注解才可以被扫描成功,
或者在启动类上添加@MapperScan(“com.yan.mapper”)进行扫描