好久没写blog了感觉自己要废了

本文使用的环境

名称 版本
OS Win
SpringBoot版本 2.4.1
JDK 1.8

0.前言

0.1 什么是durid

Druid是一个JDBC组件库,包括数据库连接池、SQL Parser等组件。 DruidDataSource是最好的数据库连接池。
Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。

阿里的开源项目druid,它不仅是一个数据库连接池,还提供了监控功能,它有以下优点:

很方便的替换dbcp和c3p0连接池;
性能比dbcp、c3p0等连接池好;
采用filter-chain责任链模式,很方便的添加监控功能以及对数据库用户名和密码加密功能

下面开始整合JPA

1. 整合JPA和Druid的配置

1.1 添加依赖

        <!-- 引入数据库的两个依赖,还有druid数据源  -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.20</version>
</dependency>

1.2 添加JPA配置

复制就完事了
application.yml 参考

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    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,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

  # jpa的一些配置
  jpa:
    generate-ddl: true
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQL57InnoDBDialect
    show-sql: true
server:
  port: 80

1.3 Druid的配置类

参考文件如下


@Configuration
public class DruidConfig {

    /*
       将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
       绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
       @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
       前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    //配置 Druid 监控管理后台的Servlet;
    //内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
        // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
        initParams.put("loginPassword", "123456"); //后台管理界面的登录密码

        //后台允许谁可以访问
        //initParams.put("allow", "localhost"):表示只有本机可以访问
        //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
        initParams.put("allow", "");
        //deny:Druid 后台拒绝谁访问
        //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问

        //设置初始化参数
        bean.setInitParameters(initParams);
        return bean;
    }

    //配置 Druid 监控 之  web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(initParams);

        //"/*" 表示过滤所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

}

2. 测试

2.1 创建一个实体类

  • Pet.java

    /**
    * @Entity 该注解表明当前是实体类,当前的实体和底层的t_pet 关系表进行了映射
    */
    @Entity(name = "t_pet")
    public class Pet {
      @Id
      //主键自增策略
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Integer id;
    
      //普通的列,这个里面有很多属性,可以就使用默认的
      @Column
      private String name;
    
      @Column
      private String color;
    
      /**
      *  get和set方法还有构造方法就省略了。
      *
      **/
    

写好这个实体类之后启动。就会自动创建表

2.2 DAO层接口层

  • PetDao.java
    public interface PetDao extends JpaSpecificationExecutor<Pet>,JpaRepository<Pet,Integer> {
    }
    
    这个接口就只要继承接口就好了

service层我就不搞了,直接上Controller层了

2.3 Controller层

@RestController
@RequestMapping("/pet")
public class PetController {
    @Autowired
    private PetDao petDao;

    /**
     * 插入宠物
     * @param name 宠物名字
     * @param color 宠物颜色
     * @return
     */
    @GetMapping("/insert")
    public String insertPet(@RequestParam("name")String name,@RequestParam("color")String color){
        Pet pet = new Pet(name,color);
        petDao.save(pet);
        return "insert success";
    }


    /**
    * 所有的宠物
    */
    @GetMapping("/list")
    public String test(){
        List<Pet> all = petDao.findAll();
        System.out.println(all);
        return all.toString();
    }


}

2.4 测试

先试试插入一条数据

插入成功!

然后试试查看所有的宠物

还有一个就是Druid的监控页面
http://localhost/druid/login.html

3 其他

3.1 Mybatis和JPA

  • 两个持久层框架,从底层到用法都不同。但是实现的功能都是一样的
  • Jpa是对象和对象之间的映射,Mybatis是对象和结果集之间的映射
  • Jpa移植性好,Mybatis需要改sql语句(如果更换数据库的话

一个好奇的人