1. 程式人生 > 實用技巧 >SpringBoot整合Mybatis連線Oracle資料庫

SpringBoot整合Mybatis連線Oracle資料庫

SpringBoot整合Mybatis連線Oracle資料庫

專案構建思路

專案構建過程可以參考Github上的springboot-guide專案:

https://github.com/Snailclimb/springboot-guide/blob/master/docs/basis/springboot-mybatis.md

由於上述專案中使用的資料庫為MySQL,而公司中大部分使用Oracle資料庫,因此在一些配置上有一定區別。

配置 pom 檔案中的相關依賴

<dependency>
    <groupId>com.svw.otd</groupId>
    <artifactId>oracle14</artifactId>
    <version>0.0.1</version>
</dependency>

該jar包是我們公司購買的Oracle Ojdbc,也可以到maven倉庫的網站上下載相應版本:

https://mvnrepository.com/

Ojdbc10 19.8.0.0:

<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc10 -->
<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc10</artifactId>
    <version>19.8.0.0</version>
</dependency>

複製到pom.xml檔案後Reload Maven Projects即可。

配置 application.properties

mybatis.mapper-locations=classpath:mapper/*.xml
spring.datasource.url=jdbc:oracle:thin:@(description=(address=(protocol=tcp)(port=port)(host=host))(connect_data=(service_name=service_name)))
spring.datasource.username=***
spring.datasource.password=******
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  • mybatis.mapper-locations指定xml檔案路徑。
  • spring.datasource.url中的port,host和service_name分別與連線資料庫時的配置對應:
  • spring.datasource.type宣告專案使用Druid資料庫連線池而非預設的Hikari。

使用xml檔案完成資料庫操作

  • Bean(實體)層
      package com.example.internet.bean;
    
      import lombok.Data;
    
      @Data
      public class Pojo {
          private Integer type;
          private String email;
          private String factory;
      }
    
  • Dao層
      package com.example.internet.dao;
      import com.example.internet.bean.Pojo;
      import org.apache.ibatis.annotations.Mapper;
    
      import java.util.List;
    
      @Mapper
      public interface Dao {
          List<Pojo> findUser();
      }
    
  • 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.example.internet.dao.Dao">
    
          <select id="findUser" resultType="com.example.internet.bean.Pojo">
              select
              USER.TYPE as type,
              USER.EMAIL as email,
              USER.FACTORY as factory
              from USER
          </select>
    
      </mapper>
    
    其中,namespace對應Dao層檔案,id對應Dao層中的方法,resultType設定返回值型別,此處返回實體層中的Pojo物件。

生成csv檔案

有時候需要將查詢得到的結果輸出為csv檔案,可使用apache commons csv庫進行相關讀寫操作。官方文件:

http://commons.apache.org/proper/commons-csv/user-guide.html

操作步驟如下:

  1. 在pom.xml檔案中新增相關依賴,更新maven project進行下載:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.8</version>
</dependency>
  1. 在專案中新增工具類
@Component
public class ExportcsvUtils {

    public void exportcsv(List<Pojo> pojoList) {
        // 設定csv表頭
        final String[] FILE_HEADER = {"Email", "Factory", "Type"};

        // 獲取當前日期並給csv檔案命名
        LocalDate dateDate = LocalDate.now();
        final String FILE_NAME = dateDate + ".csv";

        FileWriter fileWriter = null;
        CSVPrinter csvPrinter = null;
        try {
            fileWriter = new FileWriter(FILE_NAME);
            CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
            csvPrinter = new CSVPrinter(fileWriter, csvFormat);

            // 遍歷查詢結果,逐行寫入csv
            for (Pojo pojo : pojoList) {
                List<String> row = new ArrayList<>();
                Integer type = pojo.getType();
                String email = pojo.getEmail();
                String factory = pojo.getFactory();

                row.add(email);
                row.add(factory);
                row.add(type);
                csvPrinter.printRecord(row);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvPrinter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
  1. 建立定時任務,引入工具類:
@Component
public class InternetJob {
    @Autowired
    public ExportcsvUtils exportcsvUtils;

    @Autowired
    public ServiceImpl Service;

    @Scheduled(cron = "*/5 * * * * *")
    @SchedulerLock(name = "internetoutRemind", lockAtMostFor = "10m", lockAtLeastFor = "10m")
    public void showUsers() {
        List<Pojo> pojoList = this.Service.findUser();
        this.exportcsvUtils.exportcsv(pojoList);
    }
}
  • @Component:確保定時任務可以在專案build時被掃描到;
  • @Scheduled(cron = "*/5 * * * * *"):表明下方的方法每隔5秒觸發一次;
  • @SchedulerLock(name = "internetoutRemind", lockAtMostFor = "15m", lockAtLeastFor = "10m"):分散式鎖,限制任務10分鐘內只能觸發一次且15分鐘後一定會釋放鎖;
  • 最後在啟動類中加入@EnableScheduling。