mybatis-plus作为maven分模块dao层引入的配置
1.maven分模块说明
- demo-dao
- demo-web
demo-web中引用demo-dao层,进行crud
2.数据库配置放到哪里?
放到demo-web模块的application.properties
spring.datasource.driver-class-name=@mysql.driver@
spring.datasource.url=@mysql.url@
spring.datasource.username=@mysql.user@
spring.datasource.password=@mysql.pass@
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&useUnicode=true&characterEncoding=UTF-8&tinyInt1isBit=false&useCompression=true&autoReconnect=true&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&useUnicode=true&characterEncoding=UTF-8&tinyInt1isBit=false&useCompression=true&autoReconnect=true&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);
}
}
原创:做时间的朋友