Idea+maven+spring-cloud项目搭建系列--4整合mybatis-plus

  • 本位为 Idea+maven+spring-cloud项目搭建系列,maven项目的创建可以参考:
    https://blog.csdn.net/l123lgx/article/details/121467823
  • 本文使用了nacos 作为微服务的注册与发现,nacos 阿里云服务器的安装可以参考:https://blog.csdn.net/l123lgx/article/details/121421431
    nacos 服务端的配置和使用可以参考:
    https://blog.csdn.net/l123lgx/article/details/121491529

**1 创建一个 springboot 项目**在这里插入图片描述
2 项目坐标填写
在这里插入图片描述
在这里插入图片描述
3 pom 处理:

<?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>
    <!-- 1 引入父类pom -->
    <parent>
        <artifactId>bluegrass</artifactId>
        <groupId>org.lgx.bluegrass</groupId>
        <version>1.0-RELEASE</version>
    </parent>
    <groupId>org.lgx.bluegrass</groupId>
    <artifactId>bluegrass-coree</artifactId>
    <name>bluegrass-coree</name>
    <description>Demo project for Spring Boot</description>
    <version>1.0-RELEASE</version>
    <packaging>jar</packaging>

    <!-- 2 去除子类的变量引用统一使用 父类 -->
    <!--
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>
   -->
    <dependencies>
        <dependency>
            <groupId>org.lgx.bluegrass</groupId>
            <artifactId>bluegrass-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
        <!-- 增加nacos 配置 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- mysql -->
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 分页 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>


    </dependencies>
    <!-- 3 移除依赖管理 -->
    <!--
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>org.lgx.bluegrass.bluegrasscoree.BluegrassCoreeApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

4 父类pom 增加子模块:
在这里插入图片描述
5 nacos 增加对应的配置文件

在nacos 配置中心中,找到新增的命名空间,同gateway 服务配置步骤一样,发布改服务的配置即可;步骤参考:
https://blog.csdn.net/l123lgx/article/details/121487031

完整的配置文件如下:

server:
  port: 9082
version:
  number: 123
spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource  #数据源类型
    hikari:
      pool-name: KevinHikariPool  #连接池名称,默认HikariPool-1
      maximum-pool-size: 20   #最大连接数,小于等于0会被重置为默认值10;大于零小于1会被重置为minimum-idle的值
      connection-timeout: 60000 #连接超时时间:毫秒,小于250毫秒,否则被重置为默认值30秒
      minimum-idle: 10  #最小空闲连接,默认值10,小于0或大于maximum-pool-size,都会重置为maximum-pool-size
      idle-timeout: 500000   # 只有空闲连接数大于最大连接数且空闲时间超过该值,才会被释放
      max-lifetime: 600000   #连接最大存活时间.不等于0且小于30秒,会被重置为默认值30分钟.设置应该比mysql设置的超时时间短
      connection-test-query: SELECT 1   #连接测试查询
    bluegrass:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/bluegrass?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useAffectedRows=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
      username: root
      password: 123456
# 暴露全部端口
management:
  endpoints:
    web:
      exposure:
        include: '*'
mybatis-plus:
  # mapper-locations: classpath:mapper/**.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:   
    com.baomidou.example.mapper: debug 

6 微服务中增加mysql 的配置
新建config 文件夹
在这里插入图片描述

6.1 增加HikariBaseConfig.java 连接池

 import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Configuration;

/**
 * 线程池
 */
@Configuration
public class HikariBaseConfig {

    @Value("${spring.datasource.hikari.pool-name}")
    private String poolName;
    @Value("${spring.datasource.hikari.maximum-pool-size}")
    private Integer maximumPoolSize;
    @Value("${spring.datasource.hikari.connection-timeout}")
    private Long connectionTimeout;
    @Value("${spring.datasource.hikari.minimum-idle}")
    private Integer minimumIdle;
    @Value("${spring.datasource.hikari.max-lifetime}")
    private Long maxLifetime;
    @Value("${spring.datasource.hikari.connection-test-query}")
    private String connectionTestQuery;


    public HikariDataSource getDataSource(String driverClassName, String url, String username, String password){
        HikariDataSource hikariDataSource = DataSourceBuilder.create().type(HikariDataSource.class).driverClassName(driverClassName).username(username).url(url).password(password).build();
        hikariDataSource.setConnectionTestQuery(connectionTestQuery);
        hikariDataSource.setMaxLifetime(maxLifetime);
        hikariDataSource.setMinimumIdle(minimumIdle);
        hikariDataSource.setConnectionTimeout(connectionTimeout);
        hikariDataSource.setPoolName(poolName);
        hikariDataSource.setMaximumPoolSize(maximumPoolSize);
        return hikariDataSource;
    }


}

6.2 增加数据库配置文件 BluegrassDataSourceConfig.java

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.github.pagehelper.PageHelper;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Description TODO
 * @Date 2021/11/18 11:00
 * @Author lgx
 * @Version 1.0
 */
// 标明注解
@Configuration
// 开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional 便可
@EnableTransactionManagement
// 配置xml 扫描文件位置
@MapperScan(basePackages ={"org.lgx.bluegrass.bluegrasscoree.mapper"}, sqlSessionFactoryRef = "bluegrassSqlSessionFactory")
public class BluegrassDataSourceConfig {
    @Value("${spring.datasource.bluegrass.jdbc-url}")
    private String url;

    @Value("${spring.datasource.bluegrass.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.bluegrass.username}")
    private String username;

    @Value("${spring.datasource.bluegrass.password}")
    private String password;

    @Autowired
    private HikariBaseConfig hikariBaseConfig;

    @Primary
    @Bean(name = "bluegrassDataSource")
    public DataSource masterDataSource() {
        return hikariBaseConfig.getDataSource(driverClassName, url, username, password);
    }

    @Primary
    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("bluegrassDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Primary
    @Bean(name = "bluegrassSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("bluegrassDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/bluegrass/**/*.xml"));
// 全局字段创建人/更新人/创建时间/更新时间 字段的填充
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new BluegrassMetaHandler());
        sessionFactoryBean.setGlobalConfig(globalConfig);
        // sessionFactoryBean.setPlugins(new Interceptor[]{pageHelper()});
        Interceptor[] plugins = {paginationInterceptor()};
        sessionFactoryBean.setPlugins(plugins);
        return sessionFactoryBean.getObject();
    }

    @Primary
    @Bean(name = "bluegrassSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("bluegrassSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 事务管理
     *
     * @param dataSource
     * @return
     */
    @Primary
    @Bean(name = "bluegrassTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("bluegrassDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 分页插件
     */
    @Primary
    @Bean
    public PageHelper pageHelper() {
        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
   /**
 * 分页插件
 */
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor().setDialectType("mysql");
}

}

如果在nacos 配置文件中配置了自定义的mysql log 日志打印则增加
MybatisPlusCustomerOutImpl.java 日志实现类

/**
 * @Description TODO
 * @Date 2021/11/18 10:54
 * @Author lgx
 * @Version 1.0
 */
public class MybatisPlusCustomerOutImpl {
    public MybatisPlusCustomerOutImpl(String clazz) {
        System.out.println("MybatisPlusCustomerOutImpl::"+clazz);
    }

    public boolean isDebugEnabled() {
        return true;
    }

    public boolean isTraceEnabled() {
        return true;
    }

    public void error(String s, Throwable e) {
        System.err.println(s);
        e.printStackTrace(System.err);
    }

    public void error(String s) {
        System.err.println("MybatisPlusCustomerOutImpl::"+s);
    }

    public void debug(String s) {
        System.out.println("MybatisPlusCustomerOutImpl::"+s);
    }

    public void trace(String s) {
        System.out.println("MybatisPlusCustomerOutImpl::"+s);
    }

    public void warn(String s) {
        System.out.println("MybatisPlusCustomerOutImpl::"+s);
    }
}

6.3 全局字段创建人/更新人/创建时间/更新时间 字段的填充

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * @Description TODO
 * @Date 2021/11/18 11:24
 * @Author lgx
 * @Version 1.0
 */
public class BluegrassMetaHandler  implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createdBy", getCurrentUserId(), metaObject);
        this.setFieldValByName("createdTime", new Date(), metaObject);
        this.setFieldValByName("updatedBy", getCurrentUserId(), metaObject);
        this.setFieldValByName("updatedTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updatedBy", getCurrentUserId(), metaObject);
        this.setFieldValByName("updatedTime", new Date(), metaObject);
    }

    private String getCurrentUserId() {

        return "";
    }
}

6.4SqlXml 文件夹创建(注意需要和扫描路径的文件名保持一致):
在这里插入图片描述
6.5 增加实体,业务层,mapper 层进行测试:
(6.5.1) 分页查询:
(6.5.2) 增加,删除,更新:
(6.5.3)xml sql:
代码较多,百度网盘下载地址:链接: https://pan.baidu.com/s/1KLZnLnC9wBkFseni-qzSCg 提取码: fik6

参考: https://mp.baomidou.com/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值