首页 > 其他分享 >mybatis-plus作为maven分模块dao层引入的配置

mybatis-plus作为maven分模块dao层引入的配置

时间:2024-01-19 16:23:06浏览次数:31  
标签:true demo dao maven plus org import com public

1.maven分模块说明

  • demo-dao
  • demo-web

demo-web中引用demo-dao层,进行crud

2.数据库配置放到哪里?

放到demo-web模块的application.properties

[email protected]@
[email protected]@
[email protected]@
[email protected]@
spring.datasource.validationQuery=SELECT 1
spring.datasource.idle.timeout=180000
spring.datasource.maximumPoolSize=60
spring.datasource.defaultAutoCommit=true
spring.datasource.maxLifetime=1800000
spring.datasource.connectionTimeout=30000
# 扫描xml的路径,必须写
mybatis-plus.mapper-locations=classpath*:com/xxx/demo/dao/mapper/*Mapper.xml

里面@@引用的变量定义在哪?
demo-web模块的pom.xml中的profiles中


<profiles>
        <!-- 开发环境 -->
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <activeEnv>dev</activeEnv>
                <mysql.driver>com.p6spy.engine.spy.P6SpyDriver</mysql.driver>
                <mysql.url>
                    jdbc:p6spy:mysql://127.0.0.1:3358/test?rewriteBatchedStatements=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;tinyInt1isBit=false&amp;useCompression=true&amp;autoReconnect=true&amp;defaultFetchSize=100
                </mysql.url>
                <mysql.user>test</mysql.user>
                <mysql.pass>test</mysql.pass>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <activeEnv>prod</activeEnv>
                <mysql.url>
                    jdbc:p6spy:mysql://prodnet:3358/delta?rewriteBatchedStatements=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;tinyInt1isBit=false&amp;useCompression=true&amp;autoReconnect=true&amp;defaultFetchSize=100
                </mysql.url>
                <mysql.user>test_rw</mysql.user>
                <mysql.pass>test</mysql.pass>
            </properties>
        </profile>
    </profiles>

3.demo-dao层的mybatis如何引用到另一个模块里配置的变量呢

定义DataSourceProperties配置类,将springboot中的变量引用到DataSourceProperties配置类中,并引用前缀spring.datasource

@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties {
    private String url;
    private String username;
    private String password;
    private String driverClassName;

    // 省略 getter 和 setter 方法...

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }
}

4.demo-dao层如何配置相关的数据库配置呢

创建依赖3提到的properties变量的配置类来,手工生成datasource及datasourceFactory,而不使用starter
SpringConnectionFactory.java

@Slf4j
@Configuration
@MapperScan("com.jdl.demo.dao.mapper")
public class SpringConnectionFactory {


    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean(destroyMethod = "")
    public HikariDataSource dataSource() {

        HikariDataSource hikariDataSource = new HikariDataSource();

        hikariDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        hikariDataSource.setJdbcUrl(dataSourceProperties.getUrl());
        hikariDataSource.setUsername(dataSourceProperties.getUsername());
        hikariDataSource.setPassword(dataSourceProperties.getPassword());
        hikariDataSource.setConnectionTestQuery("SELECT 1");
        hikariDataSource.setConnectionTimeout(30000);
        hikariDataSource.setMaximumPoolSize(10);
        hikariDataSource.setIdleTimeout(180000);
        hikariDataSource.setAutoCommit(true);
        hikariDataSource.setMaxLifetime(1800000);
        return hikariDataSource;
    }

    @Bean
    SqlInjector deltaSqlInjector() {
        return new SqlInjector();
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisConfiguration configuration = new MybatisConfiguration();
//        configuration.setLogImpl(StdOutImpl.class);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        configuration.setCallSettersOnNulls(true);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.addInterceptor(paginationInterceptor());
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfiguration(configuration);
        sqlSessionFactoryBean.setDataSource(dataSource());

        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setIdType(IdType.AUTO);
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setDbConfig(dbConfig);
        globalConfig.setMetaObjectHandler(new MetaHandler());
        globalConfig.setSqlInjector(new SqlInjector());
        sqlSessionFactoryBean.setGlobalConfig(globalConfig);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.jdl.demo.dao.entity");
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("com/jdl/demo/dao/mapper/*Mapper.xml"));
//        sqlSessionFactoryBean.setTypeEnumsPackage("fama.cost.*.fama.cost.api.enums");
        sqlSessionFactoryBean.setTypeEnumsPackage("com.jdl.demo.api.*.enums");
        sqlSessionFactoryBean.setDatabaseIdProvider(databaseIdProvider());
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSession sqlSession() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory());
    }

    @Bean
    public DatabaseIdProvider databaseIdProvider() {
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        properties.setProperty("MySQL", "mysql");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }
}

4.1 涉及到上面配置类中的其他引用定义

SqlInjector.java

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;

import java.util.List;

public class SqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        methodList.add(new PageJoin());
        methodList.add(new InsertBatchSomeColumn());
        return methodList;
    }
}

PageJon.java

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.jdl.demo.model.WideView;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;


/**
 * 提供分页的多表关联的sql注入
 *
 * @author linqiqi
 */

public class PageJoin extends com.baomidou.mybatisplus.core.injector.AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String injectorMethodName = "pageJoin";
        SqlMethod sqlMethod = SqlMethod.SELECT_PAGE;

        // build tableNameScript
        String sqlTableNameScript = " ${j.joinType} ${j.table2Name} on ${j.tableName}.${j.tableFieldName} = ${j.table2Name}.${j.table2FieldName}";
        sqlTableNameScript = SqlScriptUtils.convertForeach(sqlTableNameScript, "joinParam.joinList", "k", "j", " ");
        sqlTableNameScript = SqlScriptUtils.convertChoose("joinParam.joinList != null  and !joinParam.joinList.isEmpty", sqlTableNameScript, "");
        sqlTableNameScript = " ${joinParam.defaultTableName} \n" + sqlTableNameScript;


        // build selectColumn
        String columnSqlScript = " ${t}.*";
        columnSqlScript = SqlScriptUtils.convertForeach(columnSqlScript, "joinParam.tableNames", "k", "t", ", ");
        columnSqlScript = SqlScriptUtils.convertIf(columnSqlScript, "joinParam.tableNames != null  and !joinParam.tableNames.isEmpty", true);
        columnSqlScript = SqlScriptUtils.convertChoose("ew.sqlSelect !=null and !ew.sqlSelect.isEmpty", "${ew.sqlSelect}", columnSqlScript);


        String sql = String.format(sqlMethod.getSql(), sqlFirst(), columnSqlScript, sqlTableNameScript, sqlWhereEntityWrapper(true, tableInfo), sqlOrderBy(tableInfo), sqlComment());

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addSelectMappedStatementForOther(mapperClass, injectorMethodName, sqlSource, WideView.class);
    }

}

MetaHandler.java

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

import java.time.LocalDateTime;


@Component
public class MetaHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("yn", 0, metaObject);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}

5.demo-dao中配置entity实体,mapper及mapper对应的xml文件

Test.java

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@TableName("test")
public class Test {
    private String name;
}

TestMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jdl.demo.dao.entity.Test;

public interface TestMapper extends BaseMapper<Test> {
}

Test.xml(resources/com/xxx/demo/dao/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.xxx.demo.dao.TestMapper">

</mapper>

树状结构

6.构建相关

demo-dao层里build相关配置,放到pom.xml里

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <useDefaultDelimiters>true</useDefaultDelimiters><!--  这是重点-->
                </configuration>
                <executions>
                    <execution>
                        <id>copy-fatjar</id>
                        <phase>install</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/build</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${project.build.directory}</directory>
                                    <include>${project.build.finalName}.${project.packaging}</include>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy resource</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/classes</outputDirectory>
                            <overwrite>true</overwrite>
                            <resources>
                                <resource>
                                    <directory>${basedir}/src/main</directory>
                                    <includes>
                                        <include>*</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <configuration>
                    <filesets>
                        <fileset>
                            <directory>src/main/resources/public</directory>
                        </fileset>
                    </filesets>
                </configuration>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </testResource>
        </testResources>
    </build>

demo-web的构建配置
pom.xml

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <!--①-->
                <excludes>
                    <exclude>application*.properties</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <!--②-->
                <filtering>true</filtering>
                <includes>
                    <include>application.properties</include>
                    <include>important.properties</include>
                    <include>application-${activatedProperties}.properties</include>
                </includes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <!--①-->
                <excludes>
                    <exclude>application*.properties</exclude>
                </excludes>
            </testResource>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>application.properties</include>
                    <include>important.properties</include>
                    <include>application-${activatedProperties}.properties</include>
                </includes>
            </testResource>
        </testResources>
    </build>

7.demo-web的启动类上开启数据库mapper扫描及包扫描

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.scheduling.annotation.EnableAsync;

@Slf4j
@EnableAsync

@ImportResource(locations = {"classpath:spring-config.xml"})
// 作用是扫描Mapper接口类。
@MapperScan("com.jdl.demo.dao.mapper")
@SpringBootApplication(
        scanBasePackages = {"com.jdl.demo"},
        exclude = {DataSourceAutoConfiguration.class, MybatisPlusAutoConfiguration.class}
)
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        log.info("---开始启动---");
        SpringApplication.run(Application.class, args);
        log.info("---启动完成,耗时{}ms---", System.currentTimeMillis() - startTime);
    }
}

标签:true,demo,dao,maven,plus,org,import,com,public
From: https://www.cnblogs.com/PythonOrg/p/17974935

相关文章

  • Maven Dependency Version:pom依赖版本固定或自动升级
    先介绍过Maven的依赖调节机制。可选依赖(Optionaldependencies)被依赖的项目主动不把可以传递的依赖传递下去,好比卖车的主动声明自己不会让买车的人买这辆车附加的保险业务。下面在解决思路中会举例说明。解决思路有了上面的知识背景,考虑使用Maven提供的Optional和Exclusions......
  • 手写 Mybatis-plus 基础架构(工厂模式+ Jdk 动态代理统一生成代理 Mapper)
    这里写目录标题前言温馨提示手把手带你解析@MapperScan源码手把手带你解析@MapperScan源码细节剖析工厂模式+Jdk代理手撕脚手架,复刻BeanDefinitionRegistryPostProcessor手撕FactoryBean代理Mapper在Spring源码中的生成流程手撕MapperProxyFactory手撕增强逻辑Invoca......
  • AT_arc115_b [ARC115B] Plus Matrix 题解
    AT_arc115_b[ARC115B]PlusMatrix题解题意给定矩阵\(C_{n\timesn}\),求两个数列\(A_n,B_n\),使得\(C_{i,j}=A_i+B_j\)。分析画出一个表格来:213243502131324可以看出来,对于任意一列\(j\),\(C_{*,j}\)都存在有\(B_j\)的贡献。那么我们......
  • 基于 SpringBoot + magic-api + Vue3 + Element Plus + amis3.0 快速开发管理系统
    Tansci-Boot基于SpringBoot2+magic-api+Vue3+ElementPlus+amis3.0快速开发管理系统Tansci-Boot是一个前后端分离后台管理系统,前端集成amis低代码前端框架,后端集成magic-api的接口快速开发框架。包含基础权限、安全认证、以及常用的一些组件功能。项目......
  • MybatisPlus集成baomidou-dynamic,多数据源配置使用、MybatisPlus分页分组等操作示例
    MybatisPlus特性无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作强大的CRUD操作:内置通用Mapper、通用Service,仅仅通过少量配置即可实现单表大部分CRUD操作,更有强大的条件构造器,满足各类使用......
  • 无涯教程-Maven - 管理依赖项
    Maven的核心功能之一是依赖管理。一旦无涯教程要处理多模块项目(由数百个模块/子项目组成),管理依赖项将是一项艰巨的任务。Maven提供了高度的控制权来管理这种情况。依存关系当一个库(如A)依赖于另一个库(如B)时,通常是一种情况。如果另一个项目C要使用A,那么该项目也需要使用库B......
  • 无涯教程-Maven - 构建自动化
    BuildAutomation定义了一种方案,一旦项目构建成功完成,相关项目的构建过程就会开始,以确保相关项目稳定。考虑一个团队正在开发项目bus-core-api,另外两个项目app-web-ui和app-desktop-ui依赖。app-web-ui项目正在使用bus-core-api项目的1.0-SNAPSHOT。<projectxmlns......
  • SAS,Stata,HLM,R,SPSS和Mplus分层线性模型HLM分析学生受欢迎程度数据|附代码数据
    全文链接:http://tecdat.cn/?p=10809最近我们被客户要求撰写关于分层线性模型的研究报告,包括一些图形和统计输出。本文用于比较六个不同统计软件程序(SAS,Stata,HLM,R,SPSS和Mplus)的两级分层线性模型的过程和输出下面介绍的六个模型都是两级分层模型的变体,也称为多级模型,这是混合模型......
  • Maven使用${revision}实现多模块版本统一管理
    父pom: <?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://mave......
  • Maven中的 scope 简单介绍
    Maven中各种scope的区别compile,默认,参与编译,测试,运行,打包等过程,大部分依赖都是这个test,仅参与测试代码的编译,运行,如junitruntime,参与测试,运行,打包,不编译,如mysql-connnectorprovided,参与编译,测试,运行,不打包,如java.servlet-apisystem,参与编译,测试,运行,不打包,从本地系统读取,......