springboot 整合mybatis、jpa(数据库:mysql,Oracle)

本文详细介绍了如何在Spring Boot项目中整合MyBatis与MySQL、Oracle数据库,并利用Druid进行数据源管理。涵盖了从依赖引入、配置到实际操作的全过程,包括实体类、接口、Mapper映射和Service的编写。
摘要由CSDN通过智能技术生成

springBoot整合数据库环境搭建

精简版:
1、整合 mybatis + mysql
  1. 导入相关依赖(mybatis ,mysql驱动,pageHelper分页插件)

    			<!-- 重点:       mybatis-spring spring 整合mybatis的包 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
            </dependency>
    			<!-- 重点:   分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.2.13</version>
            </dependency>
    			<!--重点    mysql 驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
  2. 配置yml 文件

    spring:
      datasource: #配置数据库信息
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/yf03203?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&&useSSL=false
        username: TR
        password: adminxhb
    
    # mybatis 配置,1.自动扫描mapper 下所有的xml文件;2.取别名
    mybatis: 
      mapper-locations: classpath:mapper/*.xml
      type-aliases-package: com.trkj.boot_mybatis.entity
    
    # pageHelper分页插件 配置
    pagehelper: 
      helperDialect: mysql
      reasonable: true
      supportMethodsArguments: true
      params: count=countS
    
    # 服务端口及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_jpa_oracle
    
  3. 写实体类

  4. 写接口 与 mapper映射文件

    @Mapper   // 重电
    public interface DeptDao{
        // 查询所有
        List<Dept> findAllByLimit();
    }
    
  5. 写service 分页

     // 查询所有并分页
        public List<Dept> findAll(int page,int size){
            PageHelper.startPage(page,size);  // 分页插件 PageHelper
            return deptDao.findAllByLimit();
        }
    
  6. 写controller

2、整合 mybatis + oracle
  1. 导入相关依赖(mybatis ,mysql驱动,pageHelper分页插件)

    		<!--        重点4个:-->
    				<dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.8</version>
            </dependency>
            <dependency>
                <groupId>cn.easyproject</groupId>
                <artifactId>orai18n</artifactId>
                <version>12.1.0.2.0</version>
            </dependency>
            <dependency>
                <groupId>com.oracle.database.jdbc</groupId>
                <artifactId>ojdbc8</artifactId>
                <scope>runtime</scope>
            </dependency>
     				<dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
            </dependency>
    
  2. 配置yml 文件

    spring:
      datasource: #oracle数据源配置
        driver-class-name: oracle.jdbc.driver.OracleDriver
        url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
        username: scott
        password: tiger
    
    # mybatis 配置
    mybatis:
      type-aliases-package: com.trkj.boot_mybatis_oracle.entity
      mapper-locations: classpath:mapper/*.xml
    
    # pageHelper分页插件 配置
    pagehelper:
      helperDialect: oracle
      reasonable: true
      supportMethodsArguments: true
      params: count=countS
    
    # 服务端口及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_jpa_oracle
    
  3. 写实体类

  4. 写接口 与 mapper映射文件

    @Mapper   // 重电
    public interface DeptDao{
        // 查询所有
        List<Dept> findAllByLimit();
    }
    
  5. 写service 分页

     // 查询所有并分页
        public List<Dept> findAll(int page,int size){
            PageHelper.startPage(page,size);  // 分页插件 PageHelper
            return deptDao.findAllByLimit();
        }
    
  6. 写controller

3、整合 jpa+ mysql
  1. 导入mysql 依赖

    <!--        重点2个:spring-jpa的包, mysql驱动-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>   
    
  2. yml配置文件

    spring:
      #jpa 配置
      jpa:
        database: MYSQL
        database-platform: org.hibernate.dialect.MySQL8Dialect
        show-sql: true
        format-sql: true
        hibernate:
          ddl-auto: none
    
      #配置数据源信息
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/yf03203?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&&useSSL=false
        username: TR
        password: adminxhb
    
    # 服务端口及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_jpa_oracle
    

    实体类 根据 persistence生成

    3编写接口 DeptDao.java

    public interface DeptDao extends CrudRepository<DeptEntity,Integer> {
        List<DeptEntity> findAll(Pageable pageable);  //Pageable 传入分页对象
    }
    

    4编写service DeptService.java

        // 查询所有并分页
        public List<DeptEntity> findAll(int page,int size){
            Pageable pageable = PageRequest.of(page,size);  // pageable 分页
            return deptDao.findAll(pageable);
        }
    
4、整合 jpa+ oracle
  1. 导入mysql 依赖

    <!-- 重点3个:Oracle 驱动,jpa -->			
    				<dependency>
                <groupId>com.oracle.database.jdbc</groupId>
                <artifactId>ojdbc8</artifactId>
                <scope>runtime</scope>
            </dependency> 				
    				<dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
     				<dependency>
                <groupId>cn.easyproject</groupId>
                <artifactId>orai18n</artifactId>
                <version>12.1.0.2.0</version>
            </dependency>
    
  2. yml配置文件

    spring:
      # 配置数据源
      datasource:
        driver-class-name: oracle.jdbc.driver.OracleDriver
        url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
        username: scott
        password: tiger
    
      #jpa 配置
      jpa:
        database: oracle
        database-platform: org.hibernate.dialect.OracleDialect
        show-sql: true
        format-sql: true
        hibernate:
          ddl-auto: none
    
    # 服务端口及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_jpa_oracle
    
5、整合 mybatis + mysql + Druid

同上 mybatis + mysql

不同:修改yaml配置文件

spring:
  #数据库配置
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=GMT%2B8
    username: TR
    password: adminxhb
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 使用druid数据源 --------------------- 这一句 ---------------------------------
    type: com.alibaba.druid.pool.DruidDataSource
#    druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
#      ...

# mybatis 配置
mybatis:
  type-aliases-package: com.trkj.bootmybatis.pojo
  mapper-locations: classpath:mapper/*.xml
  
# 服务端口及 项目路径
server:
  port: 8899
  servlet:
    context-path: /boot_jpa_oracle

Druid 数据源配置类

package com.trkj.boot_mybatis_mysql_druid.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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 org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Author: 大熊
 * @Description  数据源配置类
 */
@Configuration
public class DruidConfig {

    /**
     * autowired datasource config
     */
    @Autowired
    private DataSourceProperties dataSourceProperties;

    /**
     * 初始化 durid datasource
     *
     * @Return: druidDataSource  datasource instance
     */
    @Bean
    public DruidDataSource druidDataSource(){
        //https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        druidDataSource.setUsername(dataSourceProperties.getUsername());
        druidDataSource.setPassword(dataSourceProperties.getPassword());
        druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        druidDataSource.setInitialSize(0);
        druidDataSource.setMaxActive(180);
        druidDataSource.setMaxWait(60000);
        druidDataSource.setMinIdle(0);
        druidDataSource.setValidationQuery("Select 1 from DUAL");
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
        druidDataSource.setMinEvictableIdleTimeMillis(180000);
        druidDataSource.setRemoveAbandoned(true);
        druidDataSource.setRemoveAbandonedTimeout(1800);
        druidDataSource.setLogAbandoned(true);
        try {
            druidDataSource.setFilters("stat,wall,stat,log4j2");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return druidDataSource;
    }

    /**
     * 配置监控服务器
     * @return 返回监控注册的servlet对象
     * @author SimpleWu
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 添加IP白名单
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
        //servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
        // 添加控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "root");
        servletRegistrationBean.addInitParameter("loginPassword", "root2020");
        // 是否能够重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置Druid服务过滤器
     * @return 返回过滤器配置对象
     */
    @Bean
    public FilterRegistrationBean statFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
        // 忽略过滤格式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
        return filterRegistrationBean;
    }
}
6、整合 mybatis + oracle+ Druid

yml 配置

# 服务端口 及 项目路径
server:
  port: 8899
  servlet:
    context-path: /boot_mybatis_oracle_druid

spring:
  #数据库配置
  datasource:
    url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
    username: scott
    password: tiger
    driver-class-name: oracle.jdbc.driver.OracleDriver
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
#   druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
#      ...

# mybatis 配置
mybatis:
  type-aliases-package: com.trkj.bootmybatis.pojo
  mapper-locations: classpath:mapper/*.xml

数据源配置文件同 精简版mybatis+mysql+Druid

7、整合 jpa + mysql + Druid

yaml配置

spring:
  #jpa 配置
  jpa:
    database: MYSQL
    database-platform: org.hibernate.dialect.MySQL8Dialect
    show-sql: true
    format-sql: true
    hibernate:
      ddl-auto: none

  #配置数据库信息
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/yf03203?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&&useSSL=false
    username: TR
    password: adminxhb
     # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
#    druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
#      ...


# 服务端口及 项目路径
server:
  port: 8899
  servlet:
    context-path: /boot_jpa_mysql

数据源配置文件同 精简版mybatis+mysql+Druid

8、整合 jpa + oracle + Druid

yml配置文件

spring:
  # 配置数据源
  datasource:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
    username: scott
    password: tiger
       # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
#    druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
#      ...


  #jpa 配置
  jpa:
    database: oracle
    database-platform: org.hibernate.dialect.OracleDialect
    show-sql: true
    format-sql: true
    hibernate:
      ddl-auto: none

# 服务端口及 项目路径
server:
  port: 8899
  servlet:
    context-path: /boot_jpa_oracle

数据源配置文件同 精简版mybatis+mysql+Druid

傻瓜版:
1、整合 mybatis + mysql
  1. 导入 mybatis 、mysql 、pagehelper的依赖

     <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    			<!-- 重点:       mybatis-spring spring 整合mybatis的包 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
            </dependency>
    			<!-- 重点:   分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.2.13</version>
            </dependency>
    			<!--重点    mysql 驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    				
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
  2. 配置yml 文件

    spring:
      datasource: #配置数据源信息
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/yf03203?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&&useSSL=false
        username: TR
        password: adminxhb
    
    # 服务端口及 项目路径
    server: 
      port: 8899
      servlet:
        context-path: /boot_mybatis
        
    # mybatis 配置,1.自动扫描mapper 下所有的xml文件;2.取别名
    mybatis: 
      mapper-locations: classpath:mapper/*.xml
      type-aliases-package: com.trkj.boot_mybatis.entity
    
    # pageHelper分页插件 配置
    pagehelper: 
      helperDialect: mysql
      reasonable: true
      supportMethodsArguments: true
      params: count=countS
    

    tips:classpath:代表的是resource 目录 :resource/mapper/*.xml

  3. 编写实体类 Dept.java

    @Data
    @ToString
    public class Dept {
        private int deptno;
        private String dname;
        private String loc;
    }
    
  4. 编写接口 与 mapper 映射文件

    编写接口:DeptDao.java

    @Mapper   // 重点
    public interface DeptDao{
        // 根据id查询
        Dept findDeptById(int deptno);
    
        // 查询所有并分页
        List<Dept> findAllByLimit();
    }
    

    编写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.trkj.boot_mybatis.dao.DeptDao">
    
        <select id="findDeptById" resultType="com.trkj.boot_mybatis.entity.Dept">
            select * from dept where deptno = #{deptno}
        </select>
        <select id="findAllByLimit" resultType="com.trkj.boot_mybatis.entity.Dept">
            select * from dept
        </select>
    </mapper>
    
  5. 编写service :DeptService.java

    package com.trkj.boot_mybatis.service;
    
    import com.github.pagehelper.PageHelper;
    import com.trkj.boot_mybatis.dao.DeptDao;
    import com.trkj.boot_mybatis.entity.Dept;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.List;
    
    @Service
    public class DeptService {
        @Autowired
        private DeptDao deptDao;
        // 根据id查询
        public Dept findDeptById(int deptno){
            return deptDao.findDeptById(deptno);
        }
        // 查询所有并分页
        public List<Dept> findAll(int page,int size){
            PageHelper.startPage(page,size);  // 分页插件 PageHelper
            return deptDao.findAllByLimit();
        }
    }
    
  6. 编写controller DeptController.java

    package com.trkj.boot_mybatis.controller;
    
    import com.github.pagehelper.PageHelper;
    import com.trkj.boot_mybatis.entity.Dept;
    import com.trkj.boot_mybatis.service.DeptService;
    import org.springframework.beans.factory.annotation.Autowired;
    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;
    
    @RestController
    public class DeptController {
        @Autowired
        private DeptService deptService;
        @RequestMapping("findDept/{deptno}")
        public Dept findDept(@PathVariable("deptno") int deptno){
            Dept dept = deptService.findDeptById(deptno);
            return dept;
        }
        @RequestMapping("findDepts/{page}/{size}")
        public List<Dept> findDepts(@PathVariable("page") int page,@PathVariable("size")int size){
            List<Dept> list = deptService.findAll(page,size);
            return list;
        }
    }
    
2、整合 mybatis + oracle
  1. 导入Oracle依赖

      <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.4</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    <!--        重点3个:-->
    				<dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.8</version>
            </dependency>
            <dependency>
                <groupId>cn.easyproject</groupId>
                <artifactId>orai18n</artifactId>
                <version>12.1.0.2.0</version>
            </dependency>
            <dependency>
                <groupId>com.oracle.database.jdbc</groupId>
                <artifactId>ojdbc8</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
  2. yml配置文件

    spring:
      datasource: #oracle数据源配置
        driver-class-name: oracle.jdbc.driver.OracleDriver
        url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
        username: scott
        password: tiger
    
    # mybatis 配置
    mybatis:
      type-aliases-package: com.trkj.boot_mybatis_oracle.entity
      mapper-locations: classpath:mapper/*.xml
    
    # 服务器配置
    server:
      port: 8899
      servlet:
        context-path: /boot_mybatis_oracle
    
    # pageHelper分页插件 配置
    pagehelper:
      helperDialect: oracle
      reasonable: true
      supportMethodsArguments: true
      params: count=countS
    
  3. 编写实体类 Dept.java

    @Data
    @ToString
    public class Dept {
        private int deptno;
        private String dname;
        private String loc;
    }
    
    
  4. 编写接口 与 mapper映射文件

    编写接口:

    import org.apache.ibatis.annotations.Mapper;	
    @Mapper 
    public interface DeptDao {
        // 根据id 查询
        Dept findDeptById(int deptno);
    
        //查询所有
        List<Dept> findAll();
    }
    

    编写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.trkj.boot_mybatis_oracle.dao.DeptDao">
      
        <select id="findDeptById" resultType="com.trkj.boot_mybatis_oracle.entity.Dept">
            select * from DEPT where DEPTNO = #{deptno}
        </select>
        <select id="findAll" resultType="com.trkj.boot_mybatis_oracle.entity.Dept">
            select * from DEPT
        </select>
    </mapper>
    
  5. 编写service DeptService.java

    @Service
    public class DeptService {
        @Autowired
        private DeptDao deptDao;
    
        public Dept findDeptById(int deptno){
            return deptDao.findDeptById(deptno);
        }
    
        public List<Dept> findAll(int page,int size){
            PageHelper.startPage(page,size);  // 分页插件 PageHelper
            return deptDao.findAll();
        }
    }
    
  6. 编写controller DeptController.java

    @RestController
    public class DeptController {
        @Autowired
        private DeptService deptService;
        @RequestMapping("findDept/{deptno}")
        public Dept findDept(@PathVariable("deptno") int deptno){
            Dept dept = deptService.findDeptById(deptno);
            return dept;
        }
        @RequestMapping("findDepts/{page}/{size}")
        public List<Dept> findDepts(@PathVariable("page") int page,@PathVariable("size")int size){
            List<Dept> list = deptService.findAll(page,size);
            return list;
        }
    }
    

    // todo : 分页效果没出来

3、整合 jpa+ mysql
  1. 导入mysql 依赖

    <!--        重点2个:spring-jap的包, mysql驱动-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>   
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
  2. yml配置文件

    spring:
      #jpa 配置
      jpa:
        database: MYSQL
        database-platform: org.hibernate.dialect.MySQL8Dialect
        show-sql: true
        format-sql: true
        hibernate:
          ddl-auto: none
    
      #配置数据源信息
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/yf03203?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&&useSSL=false
        username: TR
        password: adminxhb
    
    # 服务端口及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_jpa_mysql
    
  3. 编写实体类 DeptEntity.java persistence自动生成的

    @Entity
    @Table(name = "dept", schema = "yf03203", catalog = "")
    public class DeptEntity {
        private Integer deptno;
        private String dname;
        private String loc;
    
        @Id
        @Column(name = "deptno")
        public Integer getDeptno() {
            return deptno;
        }
    
        public void setDeptno(Integer deptno) {
            this.deptno = deptno;
        }
    
        @Basic
        @Column(name = "dname")
        public String getDname() {
            return dname;
        }
    
        public void setDname(String dname) {
            this.dname = dname;
        }
    
        @Basic
        @Column(name = "loc")
        public String getLoc() {
            return loc;
        }
    
        public void setLoc(String loc) {
            this.loc = loc;
        }
    }
    
  4. 编写接口 DeptDao.java

    import org.springframework.data.domain.Pageable;
    import org.springframework.data.repository.CrudRepository;
    
    public interface DeptDao extends CrudRepository<DeptEntity,Integer> {
        List<DeptEntity> findAll(Pageable pageable);  //Pageable 传入分页对象
    }
    
  5. 编写service DeptService.java

    @Service
    public class DeptService {
        @Autowired
        private DeptDao deptDao;
        // 根据id查询
        public DeptEntity findDeptById(int deptno){
            return deptDao.findById(deptno).orElse(null);
        }
    
        // 查询所有并分页
        public List<DeptEntity> findAll(int page,int size){
            Pageable pageable = PageRequest.of(page,size);  // pageable 分页
            return deptDao.findAll(pageable);
        }
    }
    
  6. 编写controller DeptController.java

    @RestController
    public class DeptController {
        @Autowired
        private DeptService deptService;
        @RequestMapping("findDept/{deptno}")
        public DeptEntity findDept(@PathVariable("deptno") int deptno){
            DeptEntity dept = deptService.findDeptById(deptno);
            return dept;
        }
        @RequestMapping("findDepts/{page}/{size}")
        public List<DeptEntity> findDepts(@PathVariable("page") int page,@PathVariable("size")int size){
            List<DeptEntity> list = deptService.findAll(page,size);
            return list;
        }
    }
    
4、整合 jpa+ oracle
  1. 导入mysql 依赖

    <!-- 重点3个:Oracle 驱动,jpa -->			
    				<dependency>
                <groupId>com.oracle.database.jdbc</groupId>
                <artifactId>ojdbc8</artifactId>
                <scope>runtime</scope>
            </dependency> 				
    				<dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
     				<dependency>
                <groupId>cn.easyproject</groupId>
                <artifactId>orai18n</artifactId>
                <version>12.1.0.2.0</version>
            </dependency>
    <!-- ---- end------ -->
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
  2. yml配置文件

    spring:
      # 配置数据源
      datasource:
        driver-class-name: oracle.jdbc.driver.OracleDriver
        url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
        username: scott
        password: tiger
    
      #jpa 配置
      jpa:
        database: oracle
        database-platform: org.hibernate.dialect.OracleDialect
        show-sql: true
        format-sql: true
        hibernate:
          ddl-auto: none
    
    # 服务端口及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_jpa_oracle
    
  3. 编写实体类 DeptEntity.java persistence自动生成的

    @Entity
    @Table(name = "DEPT", schema = "SCOTT", catalog = "")
    public class DeptEntity {
        private long deptno;
        private String dname;
        private String loc;
    
        @Id
        @Column(name = "DEPTNO")
        public long getDeptno() {
            return deptno;
        }
    
        public void setDeptno(long deptno) {
            this.deptno = deptno;
        }
    
        @Basic
        @Column(name = "DNAME")
        public String getDname() {
            return dname;
        }
    
        public void setDname(String dname) {
            this.dname = dname;
        }
    
        @Basic
        @Column(name = "LOC")
        public String getLoc() {
            return loc;
        }
    
        public void setLoc(String loc) {
            this.loc = loc;
        }
    }
    
  4. 编写接口 DeptDao.java

    import org.springframework.data.domain.Pageable;
    import org.springframework.data.repository.CrudRepository;
    
    public interface DeptDao extends CrudRepository<DeptEntity,Long> {
        List<DeptEntity> findAll(Pageable pageable);  //Pageable 传入分页对象
    }
    
  5. 编写service DeptService.java

    @Service
    public class DeptService {
        @Autowired
        private DeptDao deptDao;
        // 根据id查询
        public DeptEntity findDeptById(long deptno){
            return deptDao.findById(deptno).orElse(null);
        }
    
        // 查询所有并分页
        public List<DeptEntity> findAll(int page,int size){
            Pageable pageable = PageRequest.of(page,size);  // pageable 分页
            return deptDao.findAll(pageable);
        }
    }
    
  6. 编写controller DeptController.java

    @RestController
    public class DeptController {
        @Autowired
        private DeptService deptService;
        @RequestMapping("findDept/{deptno}")
        public DeptEntity findDept(@PathVariable("deptno") int deptno){
            DeptEntity dept = deptService.findDeptById(deptno);
            return dept;
        }
        @RequestMapping("findDepts/{page}/{size}")
        public List<DeptEntity> findDepts(@PathVariable("page") int page,@PathVariable("size")int size){
            List<DeptEntity> list = deptService.findAll(page,size);
            return list;
        }
    }
    
5、整合 mybatis + mysql + Druid
  1. 导入依赖 mybatis-spring,Druid数据源,mysql驱动 ,pageHelper分页插件

    <!--        重要四个:mybatis-spring的包,Druid数据源,mysql驱动,pageHelper分页插件-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.21</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.8</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
  2. yml配置文件

    spring:
      #数据库配置
      datasource:
        url: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=GMT%2B8
        username: TR
        password: adminxhb
        driver-class-name: com.mysql.cj.jdbc.Driver
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
    #    druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
    #      ...
    
    # mybatis 配置
    mybatis:
      type-aliases-package: com.trkj.bootmybatis.pojo
      mapper-locations: classpath:mapper/*.xml
    
  3. 编写 Druid 数据源配置类

    package com.trkj.boot_mybatis_mysql_druid.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
    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 org.springframework.context.annotation.Primary;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    
    import javax.sql.DataSource;
    import java.sql.SQLException;
    
    /**
     * @Author: 大熊
     * @Description  数据源配置类
     */
    @Configuration
    public class DruidConfig {
    
        /**
         * autowired datasource config
         */
        @Autowired
        private DataSourceProperties dataSourceProperties;
    
        /**
         * 初始化 durid datasource
         *
         * @Return: druidDataSource  datasource instance
         */
        @Bean
        public DruidDataSource druidDataSource(){
            //https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(dataSourceProperties.getUrl());
            druidDataSource.setUsername(dataSourceProperties.getUsername());
            druidDataSource.setPassword(dataSourceProperties.getPassword());
            druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
            druidDataSource.setInitialSize(0);
            druidDataSource.setMaxActive(180);
            druidDataSource.setMaxWait(60000);
            druidDataSource.setMinIdle(0);
            druidDataSource.setValidationQuery("Select 1 from DUAL");
            druidDataSource.setTestOnBorrow(false);
            druidDataSource.setTestOnReturn(false);
            druidDataSource.setTestWhileIdle(true);
            druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
            druidDataSource.setMinEvictableIdleTimeMillis(180000);
            druidDataSource.setRemoveAbandoned(true);
            druidDataSource.setRemoveAbandonedTimeout(1800);
            druidDataSource.setLogAbandoned(true);
            try {
                druidDataSource.setFilters("stat,wall,stat,log4j2");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return druidDataSource;
        }
    
        /**
         * 配置监控服务器
         * @return 返回监控注册的servlet对象
         * @author SimpleWu
         */
        @Bean
        public ServletRegistrationBean statViewServlet() {
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
            // 添加IP白名单
            servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
            // 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
            //servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
            // 添加控制台管理用户
            servletRegistrationBean.addInitParameter("loginUsername", "root");
            servletRegistrationBean.addInitParameter("loginPassword", "root2020");
            // 是否能够重置数据
            servletRegistrationBean.addInitParameter("resetEnable", "false");
            return servletRegistrationBean;
        }
    
        /**
         * 配置Druid服务过滤器
         * @return 返回过滤器配置对象
         */
        @Bean
        public FilterRegistrationBean statFilter() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
            // 添加过滤规则
            filterRegistrationBean.addUrlPatterns("/*");
            // 忽略过滤格式
            filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
            return filterRegistrationBean;
        }
    }
    
  4. 编写实体类 DeptEntity.java persistence自动生成的

    @Data
    @ToString
    public class Dept {
        private int deptno;
        private String dname;
        private String loc;
    }
    
  5. 编写接口 与 mapper 映射文件

    接口:DeptDao.java

    @Mapper   // 重点
    public interface DeptDao{ 
        Dept findDeptById(int deptno); // 根据id查询
        List<Dept> findAllByLimit();   // 查询所有并分页
    }
    

    编写mapper:DeptMapper.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.trkj.boot_mybatis_mysql_druid.dao.DeptDao">
    
        <select id="findDeptById" resultType="com.trkj.boot_mybatis_mysql_druid.entity.Dept">
            select * from dept where deptno = #{deptno}
        </select>
        <select id="findAllByLimit" resultType="com.trkj.boot_mybatis_mysql_druid.entity.Dept">
            select * from dept
        </select>
    </mapper>
    
  6. 编写service DeptService.java

    @Service
    public class DeptService {
        @Autowired
        private DeptDao deptDao;
        // 根据id查询
        public Dept findDeptById(int deptno){
            return deptDao.findDeptById(deptno);
        }
        // 查询所有并分页
        public List<Dept> findAll(int page,int size){
            PageHelper.startPage(page,size);  // 分页插件 PageHelper
            return deptDao.findAllByLimit();
        }
    }
    
  7. 编写controller DeptController.java

    @RestController
    public class DeptController {
        @Autowired
        private DeptService deptService;
        @RequestMapping("findDept/{deptno}")
        public Dept findDept(@PathVariable("deptno") int deptno){
            Dept dept = deptService.findDeptById(deptno);
            return dept;
        }
        @RequestMapping("findDepts/{page}/{size}")
        public List<Dept> findDepts(@PathVariable("page") int page,@PathVariable("size")int size){
            List<Dept> list = deptService.findAll(page,size);
            return list;
        }
    }
    
6、整合 mybatis + oracle+ Druid
  1. 导入依赖 mybatis-spring,Druid数据源,mysql驱动 ,pageHelper分页插件

    <!--        重要5个 :mybatis-spring  oracle两个  Druid  分页插件-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
            </dependency>
            <dependency>
                <groupId>cn.easyproject</groupId>
                <artifactId>orai18n</artifactId>
                <version>12.1.0.2.0</version>
            </dependency>
            <dependency>
                <groupId>com.oracle.database.jdbc</groupId>
                <artifactId>ojdbc8</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.21</version>
            </dependency>
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.8</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
  2. yml配置文件

    # 服务端口 及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_mybatis_oracle_druid
    
    spring:
      #数据库配置
      datasource:
        url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
        username: scott
        password: tiger
        driver-class-name: oracle.jdbc.driver.OracleDriver
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
    #   druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
    #      ...
    
    # mybatis 配置
    mybatis:
      type-aliases-package: com.trkj.bootmybatis.pojo
      mapper-locations: classpath:mapper/*.xml
    
    #分页插件配置
    
    
  3. 编写 Druid 数据源配置类

    package com.trkj.boot_mybatis_mysql_druid.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
    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 org.springframework.context.annotation.Primary;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    
    import javax.sql.DataSource;
    import java.sql.SQLException;
    
    /**
     * @Author: 大熊
     * @Description  数据源配置类
     */
    @Configuration
    public class DruidConfig {
    
        /**
         * autowired datasource config
         */
        @Autowired
        private DataSourceProperties dataSourceProperties;
    
        /**
         * 初始化 durid datasource
         *
         * @Return: druidDataSource  datasource instance
         */
        @Bean
        public DruidDataSource druidDataSource(){
            //https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(dataSourceProperties.getUrl());
            druidDataSource.setUsername(dataSourceProperties.getUsername());
            druidDataSource.setPassword(dataSourceProperties.getPassword());
            druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
            druidDataSource.setInitialSize(0);
            druidDataSource.setMaxActive(180);
            druidDataSource.setMaxWait(60000);
            druidDataSource.setMinIdle(0);
            druidDataSource.setValidationQuery("Select 1 from DUAL");
            druidDataSource.setTestOnBorrow(false);
            druidDataSource.setTestOnReturn(false);
            druidDataSource.setTestWhileIdle(true);
            druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
            druidDataSource.setMinEvictableIdleTimeMillis(180000);
            druidDataSource.setRemoveAbandoned(true);
            druidDataSource.setRemoveAbandonedTimeout(1800);
            druidDataSource.setLogAbandoned(true);
            try {
                druidDataSource.setFilters("stat,wall,stat,log4j2");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return druidDataSource;
        }
    
        /**
         * 配置监控服务器
         * @return 返回监控注册的servlet对象
         * @author SimpleWu
         */
        @Bean
        public ServletRegistrationBean statViewServlet() {
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
            // 添加IP白名单
            servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
            // 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
            //servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
            // 添加控制台管理用户
            servletRegistrationBean.addInitParameter("loginUsername", "root");
            servletRegistrationBean.addInitParameter("loginPassword", "root2020");
            // 是否能够重置数据
            servletRegistrationBean.addInitParameter("resetEnable", "false");
            return servletRegistrationBean;
        }
    
        /**
         * 配置Druid服务过滤器
         * @return 返回过滤器配置对象
         */
        @Bean
        public FilterRegistrationBean statFilter() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
            // 添加过滤规则
            filterRegistrationBean.addUrlPatterns("/*");
            // 忽略过滤格式
            filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
            return filterRegistrationBean;
        }
    }
    
  4. 编写实体类 DeptEntity.java persistence自动生成的

    @Data
    @ToString
    public class Dept {
        private int deptno;
        private String dname;
        private String loc;
    }
    
  5. 编写接口 与 mapper 映射文件

    接口:DeptDao.java

    @Mapper   // 重点
    public interface DeptDao{ 
        Dept findDeptById(int deptno); // 根据id查询
        List<Dept> findAllByLimit();   // 查询所有并分页
    }
    

    编写mapper:DeptMapper.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.trkj.boot_mybatis_oracle_druid.dao.DeptDao">
    
        <select id="findDeptById" resultType="com.trkj.boot_mybatis_oracle_druid.entity.Dept">
            select * from dept where deptno = #{deptno}
        </select>
        <select id="findAllByLimit" resultType="com.trkj.boot_mybatis_oracle_druid.entity.Dept">
            select * from dept
        </select>
    </mapper>
    
  6. 编写service DeptService.java

    @Service
    public class DeptService {
        @Autowired
        private DeptDao deptDao;
        // 根据id查询
        public Dept findDeptById(int deptno){
            return deptDao.findDeptById(deptno);
        }
        // 查询所有并分页
        public List<Dept> findAll(int page,int size){
            PageHelper.startPage(page,size);  // 分页插件 PageHelper
            return deptDao.findAllByLimit();
        }
    }
    
  7. 编写controller DeptController.java

    @RestController
    public class DeptController {
        @Autowired
        private DeptService deptService;
        @RequestMapping("findDept/{deptno}")
        public Dept findDept(@PathVariable("deptno") int deptno){
            Dept dept = deptService.findDeptById(deptno);
            return dept;
        }
        @RequestMapping("findDepts/{page}/{size}")
        public List<Dept> findDepts(@PathVariable("page") int page,@PathVariable("size")int size){
            List<Dept> list = deptService.findAll(page,size);
            return list;
        }
    }
    
7、整合 jpa + mysql + Druid

同 jpa + mysql

需要修改的:

  • yml配置

    spring:
      #jpa 配置
      jpa:
        database: MYSQL
        database-platform: org.hibernate.dialect.MySQL8Dialect
        show-sql: true
        format-sql: true
        hibernate:
          ddl-auto: none
    
      #配置数据库信息
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/yf03203?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&&useSSL=false
        username: TR
        password: adminxhb
         # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
    #    druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
    #      ...
    
    
    # 服务端口及 项目路径
    server:
      port: 8899
      servlet:
        context-path: /boot_jpa_mysql
    
  • DruidConfig.java (数据源配置类)

    package com.trkj.boot_mybatis_mysql_druid.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
    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 org.springframework.context.annotation.Primary;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    
    import javax.sql.DataSource;
    import java.sql.SQLException;
    
    /**
     * @Author: 大熊
     * @Description  数据源配置类
     */
    @Configuration
    public class DruidConfig {
    
        /**
         * autowired datasource config
         */
        @Autowired
        private DataSourceProperties dataSourceProperties;
    
        /**
         * 初始化 durid datasource
         *
         * @Return: druidDataSource  datasource instance
         */
        @Bean
        public DruidDataSource druidDataSource(){
            //https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(dataSourceProperties.getUrl());
            druidDataSource.setUsername(dataSourceProperties.getUsername());
            druidDataSource.setPassword(dataSourceProperties.getPassword());
            druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
            druidDataSource.setInitialSize(0);
            druidDataSource.setMaxActive(180);
            druidDataSource.setMaxWait(60000);
            druidDataSource.setMinIdle(0);
            druidDataSource.setValidationQuery("Select 1 from DUAL");
            druidDataSource.setTestOnBorrow(false);
            druidDataSource.setTestOnReturn(false);
            druidDataSource.setTestWhileIdle(true);
            druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
            druidDataSource.setMinEvictableIdleTimeMillis(180000);
            druidDataSource.setRemoveAbandoned(true);
            druidDataSource.setRemoveAbandonedTimeout(1800);
            druidDataSource.setLogAbandoned(true);
            try {
                druidDataSource.setFilters("stat,wall,stat,log4j2");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return druidDataSource;
        }
    
        /**
         * 配置监控服务器
         * @return 返回监控注册的servlet对象
         * @author SimpleWu
         */
        @Bean
        public ServletRegistrationBean statViewServlet() {
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
            // 添加IP白名单
            servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
            // 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
            //servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
            // 添加控制台管理用户
            servletRegistrationBean.addInitParameter("loginUsername", "root");
            servletRegistrationBean.addInitParameter("loginPassword", "root2020");
            // 是否能够重置数据
            servletRegistrationBean.addInitParameter("resetEnable", "false");
            return servletRegistrationBean;
        }
    
        /**
         * 配置Druid服务过滤器
         * @return 返回过滤器配置对象
         */
        @Bean
        public FilterRegistrationBean statFilter() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
            // 添加过滤规则
            filterRegistrationBean.addUrlPatterns("/*");
            // 忽略过滤格式
            filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
            return filterRegistrationBean;
        }
    }
    
8、整合 jpa + oracle + Druid

yml 配置

spring:
  # 配置数据源
  datasource:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
    username: scott
    password: tiger
       # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
#    druid:   #这里可以写Druid相关的配置信息,但是写在这里太冗余了,就改成java配置类的形式配置数据源了。
#      ...


  #jpa 配置
  jpa:
    database: oracle
    database-platform: org.hibernate.dialect.OracleDialect
    show-sql: true
    format-sql: true
    hibernate:
      ddl-auto: none

# 服务端口及 项目路径
server:
  port: 8899
  servlet:
    context-path: /boot_jpa_oracle

DruidConfig.java (数据源配置类)

package com.trkj.boot_mybatis_mysql_druid.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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 org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Author: 大熊
 * @Description  数据源配置类
 */
@Configuration
public class DruidConfig {

    /**
     * autowired datasource config
     */
    @Autowired
    private DataSourceProperties dataSourceProperties;

    /**
     * 初始化 durid datasource
     *
     * @Return: druidDataSource  datasource instance
     */
    @Bean
    public DruidDataSource druidDataSource(){
        //https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        druidDataSource.setUsername(dataSourceProperties.getUsername());
        druidDataSource.setPassword(dataSourceProperties.getPassword());
        druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        druidDataSource.setInitialSize(0);
        druidDataSource.setMaxActive(180);
        druidDataSource.setMaxWait(60000);
        druidDataSource.setMinIdle(0);
        druidDataSource.setValidationQuery("Select 1 from DUAL");
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
        druidDataSource.setMinEvictableIdleTimeMillis(180000);
        druidDataSource.setRemoveAbandoned(true);
        druidDataSource.setRemoveAbandonedTimeout(1800);
        druidDataSource.setLogAbandoned(true);
        try {
            druidDataSource.setFilters("stat,wall,stat,log4j2");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return druidDataSource;
    }

    /**
     * 配置监控服务器
     * @return 返回监控注册的servlet对象
     * @author SimpleWu
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 添加IP白名单
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
        //servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
        // 添加控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "root");
        servletRegistrationBean.addInitParameter("loginPassword", "root2020");
        // 是否能够重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置Druid服务过滤器
     * @return 返回过滤器配置对象
     */
    @Bean
    public FilterRegistrationBean statFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
        // 忽略过滤格式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
        return filterRegistrationBean;
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值