一、注解版
1、导入依赖
<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>2.1.3</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.23</version>
</dependency>
查看依赖关系图
2、配置数据源相关属性
(1)新建config包DruidConfig类
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
//1 配置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.197.128");//数据库的ip地址
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;
}
}
(2)给数据库建表
department.sql
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
employee.sql
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` int(2) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
application.yml
spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.197.128:3310/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
#配置读取sql
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
这里 driver-class-name: com.mysql.jdbc.Driver。我用的springboot版本是1.5.9
还需要加入log4j的依赖
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
(3)创建JavaBean
Department
Employee
属性值与数据库一一对应
(4)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);
//插入 @Options主键
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
//更新
@Update("update department set departmentName = #{departmentName} where id = #{id}")
public int updateDept(Department department);
}
(5)Contrlloer
@RestController
public class DeptController {
//注入
@Autowired
DepartmentMapper departmentMapper;
//查询
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
Department dept = departmentMapper.getDeptById(id);
return dept;
}
//插入
@GetMapping("/dept")
public Department insertDept(Department department){
int i = departmentMapper.insertDept(department);
return department;
}
}
(6)测试
(7)问题:数据库中的属性和SQL语句的属性(last_name) 与javaBean的属性命名不同(lastName)
自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
(8)使用MapperScan批量扫描所有的Mapper接口;
在主程序入口加上@MapperScan(value = "com.example.springboot.mapper;")
@MapperScan(value = "com.example.springboot.mapper;")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
二、配置文件版
与注解在同一个文件下。
1、mapper
//@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {
//此处不用写SQL语句
//查询
public Employee getEmpById(Integer id);
//插入
public void insertEmp(Employee employee);
}
2、SQL语句配置文件
参考:https://mybatis.org/mybatis-3/getting-started.html
<?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.example.springboot.mapper.EmployeeMapper"> <!--需要改全类名-->
<!--
//查找
public Employee getEmpById(Integer id);
//插入
public void insertEmp(Employee employee);-->
<select id="getEmpById" resultType="com.example.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>
3、controller
测试查询即可
@Autowired
EmployeeMapper employeeMapper;
//查询
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id)
{
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
4、在application.yml配置文件中引入SQL配置文件的位置
#配置mybatis mapper-locations SQL映射文件
mybatis:
mapper-locations: classpath:mapper/EmployeeMapper.xml
5、测试
现在数据库中插入数据
此时发现dId这里为null,是因为没有设置驼峰命名,需要在配置文件中配置驼峰命名。
6、全局配置文件
在全局配置文件中配置驼峰命名
参考:https://mybatis.org/mybatis-3/getting-started.html
<?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>
7、在application.yml配置文件中引入全局配置文件的位置
#配置mybatis config-location全局配置文件
mybatis:
config-location: classpath:mapper/mybatis-config.xml
8、测试