IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> springboot 整合mybatis、jpa(数据库:mysql,Oracle) -> 正文阅读

[Java知识库]springboot 整合mybatis、jpa(数据库:mysql,Oracle)

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;
    }
}
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-02-26 11:16:56  更:2022-02-26 11:21:11 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 12:02:39-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码