一.简介
  对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种xxxTemplate,xxxRepository来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。

二.整合JDBC和数据源
  1.查看POM依赖:

  2.配置datasource:

  3.观察其自动装配:

  4.在其运行时,具有一个DataSourceConfiguration的类,可以实现自定义的数据源配置,默认启用tomcat.jdbc数据源,同时还支持HikariDataSource,dbcp,dbcp2等数据源,我们还可以自定义数据源:

     /**
* Generic DataSource configuration.
*/
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic { @Bean
public DataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().build();
} } 

  4.自定义的数据源使用DataSourceBulider来实现自定义数据源的装配,使用反射去创建我们自定义的数据源:

     public DataSource build() {
Class<? extends DataSource> type = getType();
DataSource result = BeanUtils.instantiate(type);
maybeGetDriverClassName();
bind(result);
return result;
}

  5.在DataSourceInitializer类中定义了一个 DataSourceInitializer implements ApplicationListener<DataSourceInitializedEvent>,该类主要可以帮助我们在程序初始化的时候自动云运行 schema-*.sql data-*.sql:

     @PostConstruct
public void init() {
if (!this.properties.isInitialize()) {
logger.debug("Initialization disabled (not running DDL scripts)");
return;
}
if (this.applicationContext.getBeanNamesForType(DataSource.class, false,
false).length > 0) {
this.dataSource = this.applicationContext.getBean(DataSource.class);
}
if (this.dataSource == null) {
logger.debug("No DataSource found so not initializing");
return;
}
runSchemaScripts();
}

  6.可以在程序运行时帮助我们执行建表语句;
  7.运行插入数据的sql语句:

     @Override
public void onApplicationEvent(DataSourceInitializedEvent event) {
if (!this.properties.isInitialize()) {
logger.debug("Initialization disabled (not running data scripts)");
return;
}
// NOTE the event can happen more than once and
// the event datasource is not used here
if (!this.initialized) {
runDataScripts();
this.initialized = true;
}
}

  8.其默认规则只需要将这些文件命名为scheme-*.sql(建表语句),data-*.sql(数据形式的sql文件);将建表语句的sql文件放置在resources文件夹下命名为schema-all(schema).sql,则将在程序运行时自动创建我们的建表语句:

  9.我们也可以在配置属性文件中直接指定schema:

  10.如果我们要操作数据库,SpringBoot还具有一个默认的自动配置:JdbcTemplateAutoConfiguration:自动配置了JdbcTemplate操纵数据库

三.数据库操纵演示
  自定义一个Controller实现数据查询:

 package com.skykuqi.springboot.datajdbc.controller;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.List;
import java.util.Map; /**
* @author : S K Y
* @version :0.0.1
*/
@Controller
public class HelloController { @Autowired
JdbcTemplate template; @ResponseBody
@GetMapping("/query")
public Map<String, Object> map() {
List<Map<String, Object>> list = template.queryForList("select * from department");
return list.get(0);
}
}

四.整合使用druid数据源
  1.引入druid:

         <!--引入druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>

  2.配置druid数据源

 package com.skykuqi.springboot.datajdbc.condig;

 import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; /**
* @author : S K Y
* @version :0.0.1
*/
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druid() {
return new DruidDataSource();
} //配置Durid的监控
//1. 配置一个管理后台的Service
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParameters = new HashMap<>();
//配置登录后台时的用户名
initParameters.put("loginUsername", "admin");
//配置登录后台的密码
initParameters.put("loginPassword", "123456");
//默认允许所有访问,配置只允许本地登录
initParameters.put("allow", "127.0.0.1");
//阻止该地址的访问
initParameters.put("deny", "192.168.1.108");
bean.setInitParameters(initParameters);
return bean;
} //2.配置一个监控的filter
@Bean
public FilterRegistrationBean webStartFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String, String> initParameters = new HashMap<>();
//设置不拦截以下请求
initParameters.put("exclusions","*.js,*.css,/druid");
//设置拦截以下所有请求
bean.setInitParameters(initParameters);
bean.setUrlPatterns(Collections.singletonList("/*"));
return bean;
}
}
 spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.1.108:3306/jdbc?useSSL=false
driver-class-name: com.mysql.jdbc.Driver
schema:
- classpath:department.sql
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

五.整合Mybatis
  1.查看POM依赖

     <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>2.1.1</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

  2.配置使用Mybatis
  (1)配置数据源相关;
  (2)在数据库中建立相关数据表
  (3)创建javaBean;
  (4)使用SpringBoot整合Mybatis;

 package com.skykuqi.springboot.mybatis.mapper;

 import com.skykuqi.springboot.mybatis.entity.Department;
import org.apache.ibatis.annotations.*; /**
* @author : S K Y
* @version :0.0.1
*/
@Mapper //指定这是一个操作数据库的mapper
public interface DepartmentMapper {
@Select("select * from department where id=#{id}")
Department queryDepartmentById(Integer id); @Delete("delete from department where id=#{id}")
int deleteDepartmentById(Integer id); @Insert("insert into department(departmentName) values(#{departmentName}) ")
int insertDepartment(Department department); @Update("update department set departmentName=#{departmentName} where id=#{id}")
int updataDepartment(Department department);
}
 package com.skykuqi.springboot.mybatis.controller;

 import com.skykuqi.springboot.mybatis.entity.Department;
import com.skykuqi.springboot.mybatis.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; /**
* @author : S K Y
* @version :0.0.1
*/
@org.springframework.web.bind.annotation.RestController
public class RestController {
@Autowired
DepartmentMapper departmentMapper; @GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id) {
return departmentMapper.queryDepartmentById(id);
} @GetMapping("/dept")
public Department insertDept(Department department) {
departmentMapper.insertDepartment(department);
return department;
}
}

  --实现插入语句的id值回显:

     @Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(departmentName) values(#{departmentName}) ")
int insertDepartment(Department department);

  (5)当javaBean中的名称与数据库中的名称不一致时.例如javaBean中为departmentName,而在数据库中为department_name,在Mybatis的自动配置中存在ConfigurationCustomizer相关的配置,我们可以自定义实现该接口:

 package com.skykuqi.springboot.mybatis.config;

 import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; /**
* @author : S K Y
* @version :0.0.1
*/
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> {
configuration.setMapUnderscoreToCamelCase(true); //开启驼峰命名法
};
}
}

  (6)可以使用@MapperScan 来配置mapper包扫描,避免过多的Mapper注解的实现

  3.使用配置文件的方式来进行Mybatis的整合
  (1)在yml配置文件中注册配置类:

  (2)在xml文件中配置启用mapUnderscoreToCamelCase

 <?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>

  (3)编写mapper.xml

 <?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.skykuqi.springboot.mybatis.mapper.EmployeeMapper">
<select id="queryEmpById" parameterType="Integer"
resultType="com.skykuqi.springboot.mybatis.entity.Employee">
select *
from employee
where id = #{id}
</select> <insert id="insertEmp" parameterType="com.skykuqi.springboot.mybatis.entity.Employee">
insert into employee(lastName, email, gender, d_id)
values (#{lastName}, #{email}, #{gender}, #{d_id})
</insert>
</mapper>

SpringBoot(九) -- SpringBoot与数据访问的更多相关文章

  1. SpringBoot系列之JDBC数据访问

    SpringBoot系列之JDBC数据访问 New->Project or Module->Spring Initializer 选择JDBC和mysql驱动,为了方便测试web等等也可以 ...

  2. SpringBoot详细研究-02数据访问

    Springboot对数据访问部分提供了非常强大的集成,支持mysql,oracle等传统数据库的同时,也支持Redis,MongoDB等非关系型数据库,极大的简化了DAO的代码,尤其是Spring ...

  3. SpringBoot:Mybatis + Druid 数据访问

    西部开源-秦疆老师:基于SpringBoot 2.1.7 的博客教程 秦老师交流Q群号: 664386224 未授权禁止转载!编辑不易 , 转发请注明出处!防君子不防小人,共勉! 简介 对于数据访问层 ...

  4. SpringBoot(3):SpringData 数据访问

    一. 简介 Spring Data是一个用于简化数据库访问,并支持云服务的开源框架:其主要目标是 使得对数据的访问变得方便快捷.对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系 ...

  5. SpringBoot(九):SpringBoot集成Mybatis

    (1)新建一个SpringBoot工程,在pom.xml中配置相关jar依赖 贴代码: <!--加载mybatis整合springboot--> <dependency> &l ...

  6. Springboot数据访问,棒棒哒!

    Springboot对数据访问部分提供了非常强大的集成,支持mysql,oracle等传统数据库的同时,也支持Redis,MongoDB等非关系型数据库,极大的简化了DAO的代码,尤其是Spring ...

  7. SpringBoot之旅第五篇-数据访问

    一.引言 大部分系统都离不开数据访问,数据库包括SQL和NOSQL,SQL是指关系型数据库,常见的有SQL Server,Oracle,MySQL(开源),NOSQL是泛指非关系型数据库,常见的有Mo ...

  8. java框架之SpringBoot(9)-数据访问及整合MyBatis

    简介 对于数据访问层,无论是 SQL 还是 NOSQL,SpringBoot 默认采用整合 SpringData 的方式进行统一处理,添加了大量的自动配置,引入了各种 Template.Reposit ...

  9. 六、SpringBoot与数据访问

    六.SpringBoot与数据访问 1.JDBC spring: datasource: username: root password: 123456 url: jdbc:mysql://192.1 ...

随机推荐

  1. Linux一键安装LNMP环境

    Linux一键安装LNMP环境 官方地址:https://lnmp.org/. 参考安装步骤:https://lnmp.org/install.html. 一键安装可以选择mysql版本.php版本, ...

  2. git log 详解 以及代码量统计

    https://git-scm.com/book/zh/v1/Git-%E5%9F%BA%E7%A1%80-%E6%9F%A5%E7%9C%8B%E6%8F%90%E4%BA%A4%E5%8E%86% ...

  3. eclipse把函数内容折叠的方法

    eclipse 将方法折叠要先启动折叠功能启用方法:Ctrl+ / (小键盘) 或者:右键点击行号左边的空白,弹出的选项中,选择“Folding”下的“Enable Folding”这样启动foldi ...

  4. Python---进阶---Tkinter---game

    一.用tkinter写一个小游戏,来随机生成我们需要的名字 # 用tkinter写一个小游戏,来随机生成我们需要的名字 import tkinter as tkimport random window ...

  5. 【NOIP2015模拟11.3】IOIOI卡片占卜

    题目 K理事长很喜欢占卜,经常用各种各样的方式进行占卜.今天,他准备使用正面写着"I",反面写着"O"的卡片为今年IOI的日本代表队占卜最终的成绩. 占卜的方法 ...

  6. JavaScript输出

    JavaScript不提供任何的内建或是打印方式 JavaScript的显示方案主要有以下四种: window.alert()  写入警告框 document.write()  写入 HTML 输出 ...

  7. spring IOC(Spring 生命周期,先1.构造方式,2,初始化方法,3,目标方法,4,销毁方法)

  8. [CSP-S模拟测试]:big(Trie树+贪心)

    题目描述 你需要在$[0,2^n)$中选一个整数$x$,接着把$x$依次异或$m$个整数$a_1~a_m$.在你选出$x$后,你的对手需要选择恰好一个时刻(刚选完数时.异或一些数后或是最后),将$x$ ...

  9. IO 输入输出流

    1) 数据流: 一组有序,有起点和终点的字节的数据序列.包括输入流和输出流.

  10. React-Native 之 GD (十八)监听 TabBarItem 点击与传值实现 点击 Item 进行刷新功能

    监听 TabBarItem 点击与传值实现 点击 Item 进行刷新功能 原版 APP 中当我们点击 首页和海淘 2个 Item 时,会马上获取最新数据个数然后进行更新,这边来实现一下这个功能. 1. ...