SpringBoot-Data

SpringBoot-Data

1、SpringData

1.1、SpringData简介

Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷。

可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。

Sping Data官网

数据库相关的启动器 :可以参考官方文档

2、整合JDBC

环境

JDK:1.8

Maven:3.6.X

SpringBoot框架:2.3.7

IDEA

2.1、新建SpringBoot项目

springDate-2-1

springDate-2-2

springDate-2-3

springDate-2-4

springDate-2-5

2.2、配置数据源

2.2.1、数据库表

CREATE DATABASE `mybatis` 

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(10) NOT NULL,
  `name` varchar(30) DEFAULT NULL,
  `pwd` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

USE `mybatis`;

insert  into `user`(`id`,`name`,`pwd`,`perms`) values 
(1,'admin','123456'),
(2,'yujian','123456'),
(3,'hello','123456');

2.2.2、yaml 配置

application.yaml

spring:
  datasource:
    username: root # 用户名
    password: 123456 # 密码
    url: jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver

springDate-2.2.2

springDate-2.2.3

2.3、使用、测试数据源

@SpringBootTest
class SpringbootDataApplicationTests {

    // 自动装配
    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        // 打印数据源
        System.out.println("数据源 ==>> " + dataSource.getClass());
        // 获取连接
        Connection connection = dataSource.getConnection();
        System.out.println("连接 ==>> " + connection);
        // 关闭连接
        connection.close();
    }
}

springDate-2.2.4

2.4、原理

两个核心类

  • DataSourceAutoConfiguration
  • DataSourceProperties

springDate-2-4

2.5、Template

在SpringBoot中拥有很多的Template : springBoot已经配置好的bean,拿来即用

  • JDBCTemplate
  • RedisTemplate
  • XXXXXTemplate

springDate-2-5

2.6、CRUD

实现增删改查

为了方便,这里只写了 Controller层,没有Dao、Service层

UserController

// 让控制器返回字符串
@RestController
public class UserController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 查询全部
    @GetMapping("/userList")
    public List<Map<String, Object>> queryUserList() {
        String sql = "select * from mybatis.user";
        // 没有 实体类,可以使用 Map ,接收
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }

    // 根据 iD 查询用户
    @GetMapping("/user/{id}")
    public List<Map<String, Object>> queryUserById(@PathVariable("id") String id) {
        String sql = "select * from mybatis.user where id = ?";

        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, id);
        return mapList;
    }

    // 添加用户
    @GetMapping("/addUser")
    public String addUser() {
        String sql = "insert into mybatis.user (id, name, pwd) values (4, '小明', '123456')";

        jdbcTemplate.execute(sql);
        return "add User Ok";
    }

    // 删除
    @GetMapping("/delete/{id}")
    public String deleteUserById(@PathVariable("id") String id) {
        String sql = "delete from mybatis.user where id =" + id;

        jdbcTemplate.execute(sql);
        return "delete User OK";
    }

    // 修改
    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") String id) {
        String sql = "update mybatis.user set name ='hello' ,pwd='15915915' where id=" + id;

        jdbcTemplate.execute(sql);
        return "update User OK";
    }
}

2.6.1、测试

springDate-2-5-1

springDate-2-5-2

3、整合Druid 数据源

3.1、Druid简介

Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。

Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。

Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。

Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。

Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。

Github地址:https://github.com/alibaba/druid/

com.alibaba.druid.pool.DruidDataSource 基本配置参数如下:

springDate-3-1

3.2、添加依赖。

项目中添加上 Druid 数据源依赖。

pom.xml

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>

3.3、指定数据源

application.yaml

spring:
  datasource:
    username: root # 用户名
    password: 123456 # 密码
    url: jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 指定数据源
    type: com.alibaba.druid.pool.DruidDataSource

springDate-3-3

3.4、使用、测试数据源

@SpringBootTest
class SpringbootDataApplicationTests {

    // 自动装配
    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        // 打印数据源
        System.out.println("数据源 ==>> " + dataSource.getClass());
        // 获取连接
        Connection connection = dataSource.getConnection();
        System.out.println("连接 ==>> " + connection);
        // 关闭连接
        connection.close();
    }
}

springDate-3-4

3.5、Druid 私有属性

Druid 私有属性 ,Spring Boot 默认是不注入这些属性值的,需要自己绑定druid 数据源专有配置

application.yaml

spring:
  datasource:
    username: root # 用户名
    password: 123456 # 密码
    url: jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 指定数据源
    type: com.alibaba.druid.pool.DruidDataSource

    #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

pom.xml

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

log4j.properties

使用log4j日志就需要一个配置文件

1、控制台输出

log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

2、保存日志文件

log4j.appender.FILE = org.apache.log4j.FileAppender 
log4j.appender.FILE.File = /log/file.log 
log4j.appender.FILE.Append = false 
log4j.appender.FILE.layout = org.apache.log4j.PatternLayout 
log4j.appender.FILE.layout.ConversionPattern = [framework] % d - % c -%- 4r [ % t] %- 5p % c % x - % m % n 

3.6、配置Druid

要实现后台监控功能

  • 因为SpringBoot 内置了servlet容器,所以没有web.xml
  • 要配置servlet 替代方法 ; ServletRegistrationBean 注册 servlet
  • ServletRegistrationBean 等同: web.xml
  • Servlet 如此 FLiter也一样 :FilterRegistrationBean

DruidConfig.java

@Configuration
public class DruidConfig {
    // 绑定配置文件 将自定义的数据源加到 容器中
    @ConfigurationProperties("spring.datasource")
    @Bean // 注册到Spring容器
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        Map<String, String> initParameters = new HashMap<>();

        /*
         * 增加配置 , Key 值是固定的
         * loginUsername 账号
         * loginPassword 密码
         * allow IP白名单,多个用逗号分割, 如果allow没有配置或者为空,则允许所有访问
         * deny IP黑名单(共同存在时,deny优先于allow)
         * */
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");

        // 添加初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }

    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        // WebStatFilter ;阿里巴巴 Druid 过滤器
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
        //所有请求进行监控处理
        bean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息  ; 不进行 统计
        bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return bean;
    }
}

初始化参数

springDate-3-6

3.6.1、测试

http://127.0.0.1:8080/druid/login.html

springDate-3-1-1

springDate-3-1-2

http://127.0.0.1:8080/userList

springDate-3-1-2

springDate-3-1-3

4、整合Mybatis

4.1、添加依赖

项目中添加Mybatis 的依赖

pom.xml

<!-- 非 SpringBoot 官方启动器,整合-->
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

4.2、准备工作

4.2.1、实体类

与数据库表表字段对应建立实体类

springDate-4-2-1

User

package com.xg.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

4.2.2、Mapper接口

Mapper层UserMapper接口和实现

方式一:使用@mapper 注解

// @Mapper 表示了这是一个 mybatis 的 mapper类
@Mapper
public interface UserMapper {
}

方式二:主启动类,开启,扫描mapper包

@SpringBootApplication
@MapperScan("com.xg.mapper")
public class Springboot05MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot05MybatisApplication.class, args);
    }
}

UserMapper

@Mapper
@Repository // 注册为组件
public interface UserMapper {
    //  查询全部用户
    List<User> queryUserList();

    //  根据 ID 查询用户
    User queryUserById(@Param("id") int id);

    //  添加用户
    void addUser(User user);

    //  删除用户
    void deleteUser(@Param("id") int id);

    //  修改用户
    void updateUser(User user);
}

4.2.3、Mapper映射文件

UserMapper接口的映射文件UserMapper.xml

UserMapper.xml 存放在 resources/mapper/ 下

springDate-4-2-3

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 绑定接口-->
<mapper namespace="com.xg.mapper.UserMapper">
    <select id="queryUserList" resultType="user">
        select *
        from mybatis.user
    </select>

    <select id="queryUserById" resultType="user">
        select *
        from mybatis.user
        where id = #{id};
    </select>

    <insert id="addUser" parameterType="user">
        insert into mybatis.user(id, name, pwd)
        values (#{id}, #{name}, #{pwd});
    </insert>

    <update id="updateUser" parameterType="user">
        update mybatis.user
        set name = #{name},
            pwd  = #{pwd}
        where id = #{id};
    </update>

    <delete id="deleteUser">
        delete from mybatis.user where id = #{id}
    </delete>
</mapper>

4.3、spring配置mybatis

添加 spring配置mybatis 别名 ……,让springBoot识别Mapper.xml

mybatis:
  # 别名
  type-aliases-package: com.xg.pojo
  # 定位 xml映射 文件 
  mapper-locations: classpath:mapper/*.xml

application.yaml

spring:
  datasource:
    username: root # 用户名
    password: 123456 # 密码
    url: jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT%2b8&useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 指定数据源
    type: com.alibaba.druid.pool.DruidDataSource

    #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: log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

mybatis:
  # 别名
  type-aliases-package: com.xg.pojo
  # 定位 xml映射 文件
  mapper-locations: classpath:mapper/*.xml

4.4、Controller

重新编辑UserController

UserController

// 让控制器返回字符串
@RestController
public class UserController {

    // 自动装配
    @Autowired
    private UserMapper userMapper;
    
    //  查询全部用户
    @GetMapping("/userList")
    public List<User> queryUserList() {
        return userMapper.queryUserList();
    }

    // 根据 iD 查询用户
    @GetMapping("/user/{id}")
    public User queryUserById(@PathVariable("id") int id) {
        return userMapper.queryUserById(id);
    }

    // 添加用户
    @GetMapping("/addUser/{id}")
    public String addUser(@PathVariable("id") int id) {
        userMapper.addUser(new User(id, "Mybatis", "123456"));
        return "add User Ok";
    }

    // 删除用户
    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        userMapper.deleteUser(id);
        return "delete User OK";
    }

    // 修改用户
    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id) {
        userMapper.updateUser(new User(id, "默认名", "15915915"));
        return "update User OK";
    }
}

4.5、测试

启动应用进行测试

springDate-4-5-1

springDate-4-5-2

5、结尾

5.1、项目结构

springDate

5.2、Spring-Data 依赖

<!-- 非 SpringBoot 官方启动器,整合Mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

<!-- 日志:log4j -->
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!-- 数据源:durid -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>
<!-- JDBC -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Mysql 驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
posted @ 2021-08-18 19:21  遇见星光  阅读(331)  评论(0编辑  收藏  举报