SpringBoot 与数据访问
一、JDBC
- 使用 Idea 集成开发工具搭建
- pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
- 使用 yml 配置文件进行配置
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://192.168.64.129:3307/jdbc?characterEncoding=UTF-8&serverTimezone=UTC
#如果使用mysql 8.0.20及以上需要指定时区 使用com.mysql.cj.jdbc.Driver,低版本的只需要把cj去掉即可
driver-class-name: com.mysql.cj.jdbc.Driver
#指定使用哪个数据源,结合自己的情况而定
#type: com.alibaba.druid.pool.DruidDataSource
效果:
1. 默认使用 com.zaxxer.hikari.HikariDataSource 作为数据源(springBoot 的版本为:2.3.3);
代码语言:javascript复制//查看DataSourceAutoConfiguration中的方法
@Configuration
@Conditional(PooledDataSourceCondition.class)
@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
@Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.Generic.class,
DataSourceJmxConfiguration.class })
protected static class PooledDataSourceConfiguration {
}
springboot 1.5.10版本 默认是使用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源;
自动配置原理:
- 参考 DataSurceConfiguration,根据配置创建数据源,默认使用 Tomcat 连接池;可以使用 spring.datasource.type 指定自定义的数据源类型‘
org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource
代码语言:javascript复制/**
* Generic DataSource configuration.
*/
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
@Bean
public DataSource dataSource(DataSourceProperties properties) {
//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build();
}
}
作用 :
② runDataScripts():运行插入的 sql 语句;
代码语言:javascript复制schema-*.sql、data-*.sql
默认规则: schema.sql , schema-all.sql
可是使用
schema:
- classpath:department.sql
指定位置
具体的参考我这篇博客详细介绍了
否则不会自动创建 sql 语句
二、整合 Driuid 数据源
pom.xml 导入依赖
代码语言:javascript复制<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
① 添加基本配置
不使用默认的配置,使用自己的配置
代码语言:javascript复制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
【DruidConfig.java】
代码语言:javascript复制@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
}
使用在测试类中启动 DegBug 启动
代码语言:javascript复制@SpringBootTest
class SpringBoot06DateJdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
// com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass());
System.out.println("*********************");
Connection conn = dataSource.getConnection();
System.out.println(conn);
conn.close();
}
}
启动:
Debug 启动出现异常,原因分析:应该在运行中缺少 log4j 的依赖,导致无法启动。
解决方法:
代码语言:javascript复制// 在pom.xml 文件中导入log4j的依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
启动配置生效
② 整合 Druid 数据源
【DruidConfig.java】
代码语言:javascript复制// 配置Druid的监控
/**
* 1、 配置一个管理后台的Servlet
*
*/
@Bean
public ServletRegistrationBean staViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","12345");
// 默认就是允许所有的访问
initParams.put("allow","");
initParams.put("deny","192.168.64.129");
bean.setInitParameters(initParams);
return bean;
}
/**
* 配置一个web监控的filter
*
*/
@Bean
public FilterRegistrationBean webStratFilert(){
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;
}
【HelloController.java】
代码语言:javascript复制@Controller
public class HelloController {
@Autowired
JdbcTemplate jdbcTemplate;
@ResponseBody
@GetMapping(value = "/query")
public Map<String, Object> map(){
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * FROM department");
return list.get(0);
}
}
测试:
三、 整合 Mybatis
代码语言:javascript复制<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
准备步骤:
- 配置数据源相关属性
spring:
datasource:
# 数据源基本配置
username: root
password: 6090
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.64.129:3307/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语句
initialization-mode: always
- 给数据库建表 在 yml 配置文件中添加
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
- 创建 javabean
public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;
//生成相应的get、set方法
}
public class Department {
private Integer id;
private String departmenName;
// 生成相应的get、set方法
}
① 注解版
【DepartmentMapper.java】
代码语言:javascript复制@Mapper
public interface DepartmentMapper {
@Select("select * from department where id = #{id}")
@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);
@Insert("insert department(department_name) values(#{departmentName})")
public int insertDept(Department department);
@Update("update departments set department_name=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
【DeptController.java】
代码语言:javascript复制@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
@GetMapping(value = "/dept/{id}")
public Department getdepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@GetMapping(value = "/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
}
测试:
出现异常,获取值不完整,原因分析 departmentName 这个属性名跟数据库的字段不一致,可以自定义增加驼峰命名来解决这个问题
代码语言:javascript复制@Configuration
public class MybatisConfig {
/**
* 自定义配置驼峰命名规则
* @return
*/
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
补充:使用 MapperScan 批量扫描所有的 Mapper 接口
代码语言:javascript复制@MapperScan(value = "com.oy.springboot06.Mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
② 配置文件版
- 在配置 yml 文件中配置
mybatis:
config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
mapper-locations: classpath:mybatis/mapper/*.xml 指定sql映射文件位置
【EmployeeMapper.class】
代码语言:javascript复制@Mapper
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);
}
【DeptController.java】
代码语言:javascript复制@RestController
public class DeptController {
@Autowired
EmployeeMapper employeeMapper;
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
}
- 结构图
【mybatis-config.xml】配置驼峰命名规则
代码语言:javascript复制<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
测试:
更多使用参照:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
四、整合 SpringData JPA
① SpringData 简介
② 整合 SpringData JPA
JPA : ORM(Object Relational Mapping)
- 编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
/**
*@Description 使用JPA注解配置映射关系
*@Author OY
*@Date 2020/9/15
*@Time 9:55
*/
@Entity // 告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和那个数据表对应;如果省略默认表民就是user
public class User {
@Id // 这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY)// 自增主键
private Integer id;
@Column(name = "last_name", length = 50) // 这是和数据表对应的一个列
private String lastName;
@Column // 省略默认的列名就是属性名
private String email;
// 省略get.set方法。。。。
}
- 编写一个 Dao 接口来操作实体类对应的数据表(Repository)
/**
*@Description 继承JpaRepository来完成对数据库的操作
*@Author OY
*@Date 2020/9/15
*@Time 10:12
*/
public interface UserRepository extends JpaRepository<User, Integer> {
}
- 基本配置 JpaProperties(yml 中)
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.64.129:3307/jpa
driver-class-name: com.mysql.cj.jdbc.Driver
initialization-mode: always
jpa:
hibernate:
# 更新或者创建数据表结构
ddl-auto: update
# 控制台显示SQL
show-sql: true
4.测试
【UserController.java】
代码语言:javascript复制@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Integer id){
User user = new User();
user.setId(id);
Example<User> example = Example.of(user);
Optional<User> one = userRepository.findOne(example);
return one.get();
}
@GetMapping("/user")
public User insertUser(User user){
User save = userRepository.save(user);
return save;
}
@GetMapping("/user/all")
public List<User> getAll(){
List<User> all = userRepository.findAll();
return all;
}
}