1. 程式人生 > >Mybatis連線DB2資料庫

Mybatis連線DB2資料庫

    前一陣子做了一個與DB2相關操作的專案,專案架構是SpringBoot+Mybatis+DB2。之前一直使用Mysql未接觸DB2,搭建配置過程中也是在網上一點點找資料,遇到了好多坑,現專案基本穩定執行,總結一下MyBatis配置連線DB2的過程。

springBoot+Mybatis

    首先搭建專案的整體框架,即springBoot與Mybatis。
    springBoot採用IDEA自動生成SpringBoot的方式File->New生成,並根據專案規範做出一定配置更改,這不是本文重點,關於SpringBoot的文章有好多,出現問題可csdn。
     工程建立完成後,進行Mybatis的配置。首先在pom.xml的dependencies中新增mybatis的依賴:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependncy>    

配置後記得在maven中更新下引入依賴。

DB2

pom.xml中引入db2的配置資訊:

<dependency>
    <groupId>
com.ibm.db2</groupId> <artifactId>db2jcc4</artifactId> <version>1.0.0</version> <scope>system</scope> <systemPath>自己建立的存放db2jcc4.jar路徑</systemPath> </dependncy> <dependency> <groupId>com.ibm.db2</groupId> <artifactId
>
db2jcc_license_cu</artifactId> <version>1.0.0</version> <scope>system</scope> <systemPath>自己建立路徑存放db2jcc_license_cu.jar路徑</systemPath> </dependncy>

其中db2jcc4.jar與db2jcc_license_cu.jar是db2的驅動包,他們不在標準maven中需手動新增到工程中,通過systemPath指明路徑進行引用。db2的驅動包下載地址,不方便下載可留言稍郵箱稍後發給你。之前有使用過db2jcc.jar,啟動的時候報了錯:java.lang.AbstractMethodError: com.ibm.db2.jcc.t4.b.isValid(I)Z,改用db2jcc4.jar後錯誤排除。

    引入jar包後,在application.properties進行jdbc配置。

spring.datasource.driverClassName=com.ibm.db2.jcc.DB2Driver
spring.datasource.url=jdbc:db2://"db2的ip""埠號"/"資料庫名稱"
spring.datasource.username="db2使用者名稱"
spring.datasource.password="db2密碼"

由此配置工作完成了,接下來可以在mapper中像mysql的方式寫db2的sql語句,db2存在tablespace的概念,使用表時select * from tablespace.table1。

本人也是剛剛接觸db2資料庫,如有問題尚請指正,共同學習,一起進步