SpringBoot MyBatis Plus 整合 达梦数据库
SpringBoot MyBatis Plus 整合 达梦数据库
一、前提条件
本篇博客以访问本地达梦数据库(DM8)为基础进行演示。(前提:本地已经安装了 DM8 数据库!)
关于 Windows 安装达梦数据库,请参考博客:Windows 安装 达梦数据库
关于 Docker 安装达梦数据库,请参考博客:Docker 安装 达梦数据库
关于 JDBC 方式操作达梦数据库,请参考博客:JDBC 方式操作 达梦数据库
关于 MyBatis Plus 操作达梦数据库,请参考博客:MyBatis Plus 操作 达梦数据库
关于 Spring 操作达梦数据库,请参考博客:Spring 操作 达梦数据库
二、准备 DM8 的驱动包
https://eco.dameng.com/download/ 中下载 达梦JDBC 驱动包,如下:
JDK 1.8 对应的 JDBC 驱动包为:DmJdbcDriver18.jar
三、SpringBoot 操作 达梦数据库
1、创建 SpringBoot 工程 dm-springboot
工程名根据实际情况命名,此处 dm-springboot 仅作为示例参考,工程结构如下:
2、工程文件
1)BigDataController.java
package com.miracle.dm.controller;
import com.miracle.dm.pojo.BigData;
import com.miracle.dm.service.BigDataService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @author: Miracle Luna
* @date: 2023/10/17 13:33
* @description:
*/
@RestController
@RequestMapping("/bigData")
public class BigDataController {
@Resource
private BigDataService bigDataService;
@GetMapping
public List<BigData> findAll() {
return bigDataService.selectList();
}
}
2)ProductCategoryController.java
package com.miracle.dm.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.miracle.dm.pojo.ProductCategory;
import com.miracle.dm.service.ProductCategoryService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* @author: Miracle Luna
* @date: 2023/10/17 13:33
* @description:
*/
@RestController
@RequestMapping("/productCategory")
public class ProductCategoryController {
@Resource
private ProductCategoryService productCategoryService;
@GetMapping
public List<ProductCategory> findAll(){
// return productCategoryService.selectList();
return productCategoryService.getBaseMapper().selectList(Wrappers.emptyWrapper());
}
@GetMapping("/insert/{name}")
public String insert(@PathVariable("name") String name){
String result = "insert successfully";
try {
productCategoryService.insert(new ProductCategory(null, name));
} catch (Exception e) {
result = "insert error: " + e.getMessage();
}
return result;
}
@GetMapping("/page")
public Page<ProductCategory> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize){
return productCategoryService.page(new Page(pageNum, pageSize), Wrappers.emptyWrapper());
}
}
3)BigDataMapper.java
package com.miracle.dm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.miracle.dm.pojo.BigData;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BigDataMapper extends BaseMapper<BigData> {
}
4)ProductCategoryMapper.java
package com.miracle.dm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.miracle.dm.pojo.ProductCategory;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ProductCategoryMapper extends BaseMapper<ProductCategory> {
}
5)BigData.java
package com.miracle.dm.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
@TableName(value = "PRODUCTION.BIG_DATA")
public class BigData {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private byte[] photo; //mybatis 将 Image 和 Blob 映射成 byte[]
private byte[] describe;
private String txt; //mybatis 将 Clob 映射成 String
}
6)ProductCategory.java
package com.miracle.dm.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
@TableName("PRODUCTION.PRODUCT_CATEGORY")
public class ProductCategory {
@TableId(value = "product_categoryid", type = IdType.AUTO)
private Integer product_categoryid;
private String name;
}
7)BigDataServiceImpl.java
package com.miracle.dm.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miracle.dm.mapper.BigDataMapper;
import com.miracle.dm.pojo.BigData;
import com.miracle.dm.service.BigDataService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author: Miracle Luna
* @date: 2023/10/17 13:36
* @description:
*/
@Service
public class BigDataServiceImpl extends ServiceImpl<BigDataMapper, BigData> implements BigDataService {
@Resource
private BigDataMapper bigDataMapper;
@Override
public List<BigData> selectList() {
return bigDataMapper.selectList(Wrappers.emptyWrapper());
}
}
8)ProductCategoryServiceImpl.java
package com.miracle.dm.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miracle.dm.mapper.ProductCategoryMapper;
import com.miracle.dm.pojo.ProductCategory;
import com.miracle.dm.service.ProductCategoryService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author: Miracle Luna
* @date: 2023/10/17 13:36
* @description:
*/
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements ProductCategoryService {
@Resource
private ProductCategoryMapper productCategoryMapper;
// @Override
// public List<ProductCategory> selectList() {
//// Wrapper<ProductCategory> wrapper = new QueryWrapper<>();
//// return productCategoryMapper.selectList(wrapper);
// return productCategoryMapper.selectList(Wrappers.emptyWrapper());
// }
@Override
public void insert(ProductCategory category) {
productCategoryMapper.insert(category);
}
// @Override
// public Page<ProductCategory> getPage() {
// return productCategoryMapper.selectPage(null, Wrappers.emptyWrapper());
// }
}
9)BigDataService.java
package com.miracle.dm.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.miracle.dm.pojo.BigData;
import java.util.List;
/**
* @author: Miracle Luna
* @date: 2023/10/17 13:34
* @description:
*/
public interface BigDataService extends IService<BigData> {
List<BigData> selectList();
}
10)ProductCategoryService.java
package com.miracle.dm.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.miracle.dm.pojo.ProductCategory;
/**
* @author: Miracle Luna
* @date: 2023/10/17 13:34
* @description:
*/
public interface ProductCategoryService extends IService<ProductCategory> {
// List<ProductCategory> selectList();
void insert(ProductCategory category);
// Page<ProductCategory> getPage();
}
11)DmApplication.java
package com.miracle.dm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DmApplication {
public static void main(String[] args) {
SpringApplication.run(DmApplication.class, args);
}
}
12)MybatisPlusConfig.java
package com.miracle.dm;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author: Miracle Luna
* @date: 2023/10/17 13:36
* @description:
*/
@Configuration
@MapperScan("com.miracle.dm.mapper")
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
* 如果不加如下配置,分页查询会出现异常
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// DM("dm", "达梦数据库")
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DM));
return interceptor;
}
}
注意:如果不配置该类,易引起分页查询异常问题。
具体现象,请参考博客:MyBatis Plus 达梦数据库 分页查询异常问题 。
13)BigDataMapper.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="dameng.dao.BigDataMapper">
</mapper>
14)ProductCategoryMapper.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="dameng.dao.ProductCategoryMapper">
</mapper>
15)application.yml
server:
port:8080
spring:
datasource:
url: jdbc:dm://localhost:5236
driver-class-name: dm.jdbc.driver.DmDriver
username: SYSDBA
password: SYSDBA
16)logback-spring.xml
SpringBoot 默认使用的是 logback 方式记录日志信息。
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 -->
<property name="LOG_HOME" value="./logs"/>
<property name="COLOR_PATTERN"
value="%black(%contextName-) %red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta( %replace(%caller{1}){'\t|Caller.{1}0|\r\n', ''})- %gray(%msg%xEx%n)"/>
<!-- 控制台输出 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder
class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名 -->
<FileNamePattern>${LOG_HOME}/dm-springboot.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数 -->
<MaxHistory>30</MaxHistory>
<!--用来指定日志文件的上限大小,那么到了这个值,就会删除旧的日志-->
<totalSizeCap>1GB</totalSizeCap>
<!--日志文件最大的大小 -->
<MaxFileSize>30MB</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n</pattern>
</encoder>
</appender>
<!--mybatis log configure -->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
17)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.14</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.miracle</groupId>
<artifactId>dm-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dm-springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- MybatisPlus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.2</version>
</dependency>
<!-- 达梦数据库 -->
<dependency>
<groupId>dm.jdbc</groupId>
<artifactId>DmJdbcDriver18</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.14</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
注意: 此处达梦数据库的 JDBC 驱动包 DmJdbcDriver18.jar,可以通过在工程目录下创建 lib 目录,将 jar copy到 lib,然后将 lib 目录设置添加到 Libararies 的方式,但是项目整体打包的时候,lib 目录下的 DmJdbcDriver18.jar 不会被打入到工程包中;
因此,需要将 DmJdbcDriver18.jar 添加到本地的 maven 仓库中,从本地引用 DmJdbcDriver18.jar 的依赖,在 maven 打包的时候,可以正常被打入到整体包中。
效果如下:
关于达梦数据库驱动包安装到本地 Maven 仓库的具体操作步骤,请参考博客:将达梦数据库的JDBC驱动包 DmJdbcDriver18.jar 安装到本地 Maven 仓库
3、运行结果
1)运行启动类 DmApplicatin.java
在工程目录下,自动生成日志目录 logs 和日志文件 dm-springboot.2023-10-18.0.log,效果如下:
2)浏览器中调用查询接口
示例1:
http://localhost:8080/bigData
执行效果如下:
示例2:
http://localhost:8080/productCategory
执行效果如下:
3)浏览器中调用插入接口
http://localhost:8080/productCategory/insert/测试
执行效果如下:
4)浏览器中调用插入接口
http://localhost:8080/productCategory/page?pageNum=1&pageSize=3
执行效果如下:
PS:
DbType.java 文件中枚举出了 MyBatis Plus 目前所支持的所有数据库类型,文件内容如下:
package com.baomidou.mybatisplus.annotation;
public enum DbType {
MYSQL("mysql", "MySql数据库"),
MARIADB("mariadb", "MariaDB数据库"),
ORACLE("oracle", "Oracle11g及以下数据库(高版本推荐使用ORACLE_NEW)"),
ORACLE_12C("oracle12c", "Oracle12c+数据库"),
DB2("db2", "DB2数据库"),
H2("h2", "H2数据库"),
HSQL("hsql", "HSQL数据库"),
SQLITE("sqlite", "SQLite数据库"),
POSTGRE_SQL("postgresql", "Postgre数据库"),
SQL_SERVER2005("sqlserver2005", "SQLServer2005数据库"),
SQL_SERVER("sqlserver", "SQLServer数据库"),
DM("dm", "达梦数据库"),
XU_GU("xugu", "虚谷数据库"),
KINGBASE_ES("kingbasees", "人大金仓数据库"),
PHOENIX("phoenix", "Phoenix HBase数据库"),
GAUSS("zenith", "Gauss 数据库"),
CLICK_HOUSE("clickhouse", "clickhouse 数据库"),
GBASE("gbase", "南大通用(华库)数据库"),
GBASE_8S("gbase-8s", "南大通用数据库 GBase 8s"),
/** @deprecated */
@Deprecated
GBASEDBT("gbasedbt", "南大通用数据库"),
/** @deprecated */
@Deprecated
GBASE_INFORMIX("gbase 8s", "南大通用数据库 GBase 8s"),
SINODB("sinodb", "星瑞格数据库"),
OSCAR("oscar", "神通数据库"),
SYBASE("sybase", "Sybase ASE 数据库"),
OCEAN_BASE("oceanbase", "OceanBase 数据库"),
FIREBIRD("Firebird", "Firebird 数据库"),
HIGH_GO("highgo", "瀚高数据库"),
CUBRID("cubrid", "CUBRID数据库"),
GOLDILOCKS("goldilocks", "GOLDILOCKS数据库"),
CSIIDB("csiidb", "CSIIDB数据库"),
SAP_HANA("hana", "SAP_HANA数据库"),
IMPALA("impala", "impala数据库"),
VERTICA("vertica", "vertica数据库"),
XCloud("xcloud", "行云数据库"),
REDSHIFT("redshift", "亚马逊redshift数据库"),
OPENGAUSS("openGauss", "华为 opengauss 数据库"),
TDENGINE("TDengine", "TDengine数据库"),
INFORMIX("informix", "Informix数据库"),
UXDB("uxdb", "优炫数据库"),
LEALONE("lealone", "Lealone数据库"),
OTHER("other", "其他数据库");
private final String db;
private final String desc;
public static DbType getDbType(String dbType) {
DbType[] var1 = values();
int var2 = var1.length;
for(int var3 = 0; var3 < var2; ++var3) {
DbType type = var1[var3];
if (type.db.equalsIgnoreCase(dbType)) {
return type;
}
}
return OTHER;
}
public String getDb() {
return this.db;
}
public String getDesc() {
return this.desc;
}
private DbType(final String db, final String desc) {
this.db = db;
this.desc = desc;
}
}
其中,达梦数据库 对应的枚举值为 DM。