Spring-boot 之 SpringData
1.SpringData简介
对于数据访问层,无论是 SQL ,NoSQL,在SpringBoot 底层都是采用 SpringData 来进行封装的!
SpringData也是和 SpringBoot、SpringCloud齐名的项目!
官网地址
使用IDEA构建项目的时候,可以选择SpringData;
工具,供我们直接使用,这里面封装了大量的模板;
xxxTempleate;就可以直接操作功能了!十分的方便!
2.集成JDBC
a.创建项目
b.导入数据库驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
c.编写配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: Haishao123
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
d.测试
- 测试连接
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
- 测试CRUD
package com.michael.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/jdbc")
public class JdbcController {
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/departments")
public List<Map<String,Object>> departments(){
String sql = "select * from department";
List<Map<String,Object>> lists = jdbcTemplate.queryForList(sql);
return lists;
}
@GetMapping("/add")
public String addUer(){
String sql = "insert into department(id, department_name) values(106,'HR部门')";
jdbcTemplate.update(sql);
return "ok";
}
@GetMapping("/update/{id}")
public String updateUser(@PathVariable("id") int id){
String sql = "update department set department_name=? where id="+id;
Object[] object = new Object[1];
object[0] = "人力资源部";
jdbcTemplate.update(sql,object);
return "update user "+id+" ok";
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable("id") int id){
String sql = "delete from department where id=?";
jdbcTemplate.update(sql,id);
return "delete user "+ id + " ok";
}
}
e.自动配置核心类
- DataSourceConfiguration 自动配置的数据源;
- DataSourceAutoConfiguration 自动配置类;
- DataSourceProperties 配置文件绑定!
- HikariDataSource 号称当前 Java Web速度最快的数据源,和 Druid相比,效率会更高一点!
不同的数据源拥有不同的配置;
3.集成Druid
a.简介
Java程序很大的一部分都是要操作数据库的,为了提高操作数据库的性能,所以一般会使用连接池!
Druid 是阿里巴巴的开源组件之一,结合了C3P0,DBCP的优点,并且自带日志监控!
Druid 可以天然的监控 SQL 和 数据库连接池的状况!
任何池化技术,道理都是想通的,配置参数达到更高的性能,思考的时候对比我们之前学习的线程池!
b.配置参数
c.配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: Haishao123
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
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,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
4.集成Mybatis
mybatis参考教程:
https://www.cnblogs.com/whgk/category/981571.html
Mybatis三个服务官方地址:
MyBatis:
MyBatis-Spring:
MyBatis Spring Boot Starter:
a.MyBatis 使用
1、导入依赖
2、编写mybatis配置文件
3、编写接口
4、编写接口Mapper配置文件
5、注册Mapper配置文件
6、测试
b.MyBatis-Spring
需要集成的MyBatis-Spring
上面原生的对象被Spring托管了,我们拿来即用!
c.MyBatis Spring Boot Starter
- 依赖要求
- 1、导入依赖
<!-- mybatis 是自己写的启动器不是官方的-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
- 2、编写mybatis配置文件
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.michael.pojo
mybatis.mapper-locations=classpath:com/michael/mapper/xml/*.xml
spring:
datasource:
username: root
password: Haishao123
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
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,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 3、编写实体类
package com.michael.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private Integer department;
private Date birth;
//define redundancy field to avoid to use select with multiple tables
private Department eDepartment;
}
- 4、编写接口Mapper配置文件
import com.michael.pojo.Employee;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface EmployeeMapper {
List<Employee> getEmployees();
Employee get(Integer id);
int save(Employee employee);
int delete(Integer id);
}
- 5、注册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.michael.mapper.EmployeeMapper">
<!--绑定接口中的方法-->
<!--多表有映射需要使用resultMap-->
<!--结果集映射-->
<resultMap id="EmployeeMap" type="Employee">
<!-- id代表主键 property对象的属性 column 代表数据库的列名-->
<id property="id" column="eid"/>
<!-- result普通字段 -->
<result property="lastName" column="last_name"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<result property="birth" column="birth"/>
<!--对象和集合就需要使用多对一和一对多的知识
association 关联
collection 集合包含
-->
<association property="eDepartment" javaType="Department">
<id property="id" column="did"></id>
<result property="departmentName" column="dname"></result>
</association>
</resultMap>
<select id="getEmployees" resultMap="EmployeeMap">
select e.id as eid,last_name,email,gender,birth,d.id as did,d.department_name as dname
from employee e,department d
where e.department = d.id
</select>
<insert id="save" parameterType="Employee">
insert into employee (last_name, email, gender, department, birth)
values (#{lastName}, #{email}, #{gender}, #{department}, #{birth})
</insert>
<select id="get" resultType="Employee">
select * from employee where id = #{id}
</select>
<delete id="delete" parameterType="int">
delete from employee where id = #{id}
</delete>
</mapper>
- 6、编写controller
package com.michael.controller;
import com.michael.mapper.EmployeeMapper;
import com.michael.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
@RestController
public class EmployeeController {
@Autowired
EmployeeMapper employeeMapper;
@GetMapping("/getEmployees")
public List<Employee> getEmployees(){
return employeeMapper.getEmployees();
}
@GetMapping("/getEmployee/{id}")
public Employee getEmployee(@PathVariable("id") Integer id){
return employeeMapper.get(id);
}
@GetMapping("/delete/{id}")
public int delete(@PathVariable("id") Integer id){
return employeeMapper.delete(id);
}
@GetMapping("/save")
public int save(){
Employee employee = new Employee();
employee.setLastName("qinjiang");
employee.setEmail("24736743@qq.com");
employee.setGender(1);
employee.setDepartment(101);
employee.setBirth(new Date());
return employeeMapper.save(employee);
}
}
- 7、Maven资源过滤问题
<!--Maven默认不支持从/src/java目录下获取除了代码之外的配置文件,需要过滤处理一下-->
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
- 8、测试