纯 Java 项目(非 SpringBoot)集成 Mybatis-Plus 和 Mybatis-Plus-Join
1、依赖
2、代码 2.1、SqlSession 构造器 2.2、MybatisPlus代码生成器 2.3、获取 config.yml 配置 2.3.1、config.yml 2.3.2、项目配置类
2.4、ftl 模板 2.4.1、实体类 2.4.2、Mybatis-Plus Join Mapper 接口
3、测试类 3.1、非线程安全 3.2、线程安全 3.3、MybatisPlusJoin 3.4、代码生成器
1、依赖
1.1、依赖版本
依赖 版本 Mysql-Connector-J 9.3.0 HikariCP 5.1.0 SnakeYaml 2.4 Lombok 1.18.38 Mybatis-Plus 3.5.9 Mybatis-Plus Generator 3.5.9 Mybatis-Plus-Join 1.4.13 Spring-Core 5.3.39
1.2、pom.xml
< project xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xmlns = " http://maven.apache.org/POM/4.0.0"
xsi: schemaLocation= " http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
< modelVersion> 4.0.0</ modelVersion>
< groupId> com.wxhnyfy</ groupId>
< artifactId> maven-mybatis-plus</ artifactId>
< version> 1.0</ version>
< packaging> jar</ packaging>
< name> maven-mybatis-plus</ name>
< url> http://maven.apache.org</ url>
< properties>
< java.version> 11</ java.version>
< project.build.sourceEncoding> UTF-8</ project.build.sourceEncoding>
< junit.version> 4.13.1</ junit.version>
< mybatis-plus.version> 3.5.9</ mybatis-plus.version>
< mybatis-plus-join.version> 1.4.13</ mybatis-plus-join.version>
< org.apache.logging.log4j.version> 2.23.1</ org.apache.logging.log4j.version>
< slf4j-reload4j.version> 2.0.12</ slf4j-reload4j.version>
< mysql-connector-java.version> 9.3.0</ mysql-connector-java.version>
< hikaricp.version> 5.1.0</ hikaricp.version>
< freemarker.version> 2.3.32</ freemarker.version>
< fastjson2.version> 2.0.51</ fastjson2.version>
< vfs.version> 3.3.2.Final</ vfs.version>
< lombok.version> 1.18.38</ lombok.version>
< snakeyaml.version> 2.4</ snakeyaml.version>
< commons-io.version> 2.19.0</ commons-io.version>
< spring-core.version> 5.3.39</ spring-core.version>
</ properties>
< dependencies>
< dependency>
< groupId> org.apache.logging.log4j</ groupId>
< artifactId> log4j-core</ artifactId>
< version> ${org.apache.logging.log4j.version}</ version>
</ dependency>
< dependency>
< groupId> org.apache.logging.log4j</ groupId>
< artifactId> log4j-api</ artifactId>
< version> ${org.apache.logging.log4j.version}</ version>
</ dependency>
< dependency>
< groupId> org.slf4j</ groupId>
< artifactId> slf4j-reload4j</ artifactId>
< version> ${slf4j-reload4j.version}</ version>
</ dependency>
< dependency>
< groupId> junit</ groupId>
< artifactId> junit</ artifactId>
< version> ${junit.version}</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> org.freemarker</ groupId>
< artifactId> freemarker</ artifactId>
< version> ${freemarker.version}</ version>
</ dependency>
< dependency>
< groupId> com.alibaba.fastjson2</ groupId>
< artifactId> fastjson2</ artifactId>
< version> ${fastjson2.version}</ version>
</ dependency>
< dependency>
< groupId> org.jboss</ groupId>
< artifactId> jboss-vfs</ artifactId>
< version> ${vfs.version}</ version>
</ dependency>
< dependency>
< groupId> org.projectlombok</ groupId>
< artifactId> lombok</ artifactId>
< version> ${lombok.version}</ version>
</ dependency>
< dependency>
< groupId> org.yaml</ groupId>
< artifactId> snakeyaml</ artifactId>
< version> ${snakeyaml.version}</ version>
</ dependency>
< dependency>
< groupId> commons-io</ groupId>
< artifactId> commons-io</ artifactId>
< version> ${commons-io.version}</ version>
</ dependency>
< dependency>
< groupId> com.zaxxer</ groupId>
< artifactId> HikariCP</ artifactId>
< version> ${hikaricp.version}</ version>
< exclusions>
< exclusion>
< groupId> org.slf4j</ groupId>
< artifactId> slf4j-api</ artifactId>
</ exclusion>
</ exclusions>
</ dependency>
< dependency>
< groupId> com.mysql</ groupId>
< artifactId> mysql-connector-j</ artifactId>
< version> ${mysql-connector-java.version}</ version>
</ dependency>
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus</ artifactId>
< version> ${mybatis-plus.version}</ version>
</ dependency>
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-extension</ artifactId>
< version> ${mybatis-plus.version}</ version>
</ dependency>
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-generator</ artifactId>
< version> ${mybatis-plus.version}</ version>
</ dependency>
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-jsqlparser</ artifactId>
< version> ${mybatis-plus.version}</ version>
</ dependency>
< dependency>
< groupId> com.github.yulichang</ groupId>
< artifactId> mybatis-plus-join</ artifactId>
< version> ${mybatis-plus-join.version}</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-core</ artifactId>
< version> ${spring-core.version}</ version>
</ dependency>
</ dependencies>
< build>
< resources>
< resource>
< directory> src/main/resources</ directory>
< includes>
< include> **</ include>
</ includes>
</ resource>
< resource>
< directory> src/main/java</ directory>
< includes>
< include> **/*.xml</ include>
</ includes>
</ resource>
</ resources>
< testResources>
< testResource>
< directory> src/main/resources</ directory>
< includes>
< include> **</ include>
</ includes>
</ testResource>
< testResource>
< directory> src/main/java</ directory>
< includes>
< include> **/*.xml</ include>
</ includes>
</ testResource>
</ testResources>
< plugins>
< plugin>
< groupId> org.apache.maven.plugins</ groupId>
< artifactId> maven-compiler-plugin</ artifactId>
< version> 3.3</ version>
< configuration>
< source> ${java.version}</ source>
< target> ${java.version}</ target>
< encoding> ${project.build.sourceEncoding}</ encoding>
</ configuration>
</ plugin>
</ plugins>
</ build>
</ project>
2、代码
2.1、SqlSession 构造器
package com. wxhnyfy ;
import com. alibaba. fastjson2. JSON ;
import com. alibaba. fastjson2. JSONWriter ;
import com. baomidou. mybatisplus. annotation. DbType ;
import com. baomidou. mybatisplus. core. MybatisConfiguration ;
import com. baomidou. mybatisplus. core. config. GlobalConfig ;
import com. baomidou. mybatisplus. core. injector. DefaultSqlInjector ;
import com. baomidou. mybatisplus. core. mapper. BaseMapper ;
import com. baomidou. mybatisplus. core. toolkit. GlobalConfigUtils ;
import com. baomidou. mybatisplus. core. incrementer. DefaultIdentifierGenerator ;
import com. baomidou. mybatisplus. extension. plugins. MybatisPlusInterceptor ;
import com. baomidou. mybatisplus. extension. plugins. inner. PaginationInnerInterceptor ;
import com. github. yulichang. base. MPJBaseMapper ;
import com. github. yulichang. injector. MPJSqlInjector ;
import com. github. yulichang. interceptor. MPJInterceptor ;
import com. zaxxer. hikari. HikariDataSource ;
import org. apache. ibatis. builder. xml. XMLMapperBuilder ;
import org. apache. ibatis. mapping. Environment ;
import org. apache. ibatis. plugin. Interceptor ;
import org. apache. ibatis. session. SqlSession ;
import org. apache. ibatis. session. SqlSessionFactory ;
import org. apache. ibatis. session. SqlSessionFactoryBuilder ;
import org. apache. ibatis. session. SqlSessionManager ;
import org. apache. ibatis. transaction. jdbc. JdbcTransactionFactory ;
import org. slf4j. Logger ;
import org. slf4j. LoggerFactory ;
import javax. sql. DataSource ;
import java. io. File ;
import java. io. FileInputStream ;
import java. io. IOException ;
import java. io. InputStream ;
import java. net. JarURLConnection ;
import java. net. URL ;
import java. util. Enumeration ;
import java. util. jar. JarEntry ;
import java. util. jar. JarFile ;
public class GetSqlSession {
private static final Logger logger = LoggerFactory . getLogger ( GetSqlSession . class ) ;
private static final ProjectConfiguration CONFIGURATION = ProjectConfiguration . getConfiguration ( ) ;
private static SqlSession sqlSession;
private static SqlSessionFactory sqlSessionFactory;
private static SqlSessionManager sqlSessionManager;
private static void setMybatisPlusSqlSessionFactory ( ) {
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder ( ) ;
MybatisConfiguration configuration = new MybatisConfiguration ( ) ;
GlobalConfig globalConfig = new GlobalConfig ( ) ;
globalConfig. setDbConfig ( new GlobalConfig. DbConfig ( ) ) ;
globalConfig. setSqlInjector ( new DefaultSqlInjector ( ) ) ;
globalConfig. setIdentifierGenerator ( DefaultIdentifierGenerator . getInstance ( ) ) ;
globalConfig. setSuperMapperClass ( BaseMapper . class ) ;
GlobalConfigUtils . setGlobalConfig ( configuration, globalConfig) ;
initConfiguration ( configuration) ;
Environment environment = new Environment ( "1" , new JdbcTransactionFactory ( ) , initDataSource ( ) ) ;
configuration. setEnvironment ( environment) ;
try {
registryMapperXml ( configuration, CONFIGURATION . getMybatisPlusConfiguration ( ) . getMapperConfiguration ( ) . getXmlPackage ( ) ) ;
} catch ( IOException e) {
throw new RuntimeException ( e) ;
}
sqlSessionFactory = sqlSessionFactoryBuilder. build ( configuration) ;
}
private static void setMybatisPlusJoinSqlSessionFactory ( ) {
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder ( ) ;
MybatisConfiguration configuration = new MybatisConfiguration ( ) ;
configuration. addInterceptor ( new MPJInterceptor ( ) ) ;
GlobalConfig globalConfig = new GlobalConfig ( ) ;
globalConfig. setDbConfig ( new GlobalConfig. DbConfig ( ) ) ;
globalConfig. setSqlInjector ( new MPJSqlInjector ( ) ) ;
globalConfig. setIdentifierGenerator ( DefaultIdentifierGenerator . getInstance ( ) ) ;
globalConfig. setSuperMapperClass ( MPJBaseMapper . class ) ;
GlobalConfigUtils . setGlobalConfig ( configuration, globalConfig) ;
initConfiguration ( configuration) ;
Environment environment = new Environment ( "1" , new JdbcTransactionFactory ( ) , initDataSource ( ) ) ;
configuration. setEnvironment ( environment) ;
try {
registryMapperXml ( configuration, CONFIGURATION . getMybatisPlusConfiguration ( ) . getMapperConfiguration ( ) . getXmlPackage ( ) ) ;
} catch ( IOException e) {
throw new RuntimeException ( e) ;
}
logger. debug ( "已注册的方法:{}" , JSON . toJSONString ( configuration. getMappedStatementNames ( ) , JSONWriter. Feature. WriteMapNullValue ) ) ;
sqlSessionFactory = sqlSessionFactoryBuilder. build ( configuration) ;
}
public static SqlSession getMybatisPlusSqlSession ( ) {
if ( sqlSession == null ) {
setMybatisPlusSqlSessionFactory ( ) ;
sqlSession = sqlSessionFactory. openSession ( true ) ;
}
return sqlSession;
}
public static SqlSessionManager safeMybatisPlusSqlSession ( ) {
if ( sqlSessionManager == null ) {
setMybatisPlusSqlSessionFactory ( ) ;
sqlSessionManager = SqlSessionManager . newInstance ( sqlSessionFactory) ;
}
return sqlSessionManager;
}
public static SqlSessionManager safeMybatisPlusJoinSqlSession ( ) {
if ( sqlSessionManager == null ) {
setMybatisPlusJoinSqlSessionFactory ( ) ;
sqlSessionManager = SqlSessionManager . newInstance ( sqlSessionFactory) ;
}
return sqlSessionManager;
}
public static void cleanSqlSession ( ) {
if ( sqlSession != null ) {
sqlSession. clearCache ( ) ;
}
}
public static void cleanSqlSessionManager ( ) {
if ( sqlSessionManager != null ) {
sqlSessionManager. clearCache ( ) ;
}
}
private static void initConfiguration ( MybatisConfiguration configuration) {
configuration. setMapUnderscoreToCamelCase ( CONFIGURATION . getMybatisPlusConfiguration ( ) . getMapperConfiguration ( ) . isMapUnderscoreToCamelCase ( ) ) ;
configuration. setUseGeneratedKeys ( CONFIGURATION . getMybatisPlusConfiguration ( ) . getMapperConfiguration ( ) . isUseGeneratedKeys ( ) ) ;
configuration. addInterceptor ( initInterceptor ( ) ) ;
configuration. addMappers ( CONFIGURATION . getMybatisPlusConfiguration ( ) . getMapperConfiguration ( ) . getMapperPackage ( ) ) ;
}
private static DataSource initDataSource ( ) {
HikariDataSource dataSource = new HikariDataSource ( ) ;
dataSource. setJdbcUrl ( CONFIGURATION . getJdbc ( ) . getUrl ( ) ) ;
dataSource. setDriverClassName ( CONFIGURATION . getJdbc ( ) . getDriverClassName ( ) ) ;
dataSource. setUsername ( CONFIGURATION . getJdbc ( ) . getUsername ( ) ) ;
dataSource. setPassword ( CONFIGURATION . getJdbc ( ) . getPassword ( ) ) ;
dataSource. setIdleTimeout ( 60000 ) ;
dataSource. setAutoCommit ( true ) ;
dataSource. setMaximumPoolSize ( 5 ) ;
dataSource. setMinimumIdle ( 1 ) ;
dataSource. setMaxLifetime ( 60000 * 10 ) ;
dataSource. setConnectionTestQuery ( "SELECT 1" ) ;
return dataSource;
}
private static Interceptor initInterceptor ( ) {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor ( ) ;
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor ( ) ;
paginationInnerInterceptor. setDbType ( DbType . MYSQL ) ;
paginationInnerInterceptor. setOverflow ( true ) ;
paginationInnerInterceptor. setMaxLimit ( 200L ) ;
interceptor. addInnerInterceptor ( paginationInnerInterceptor) ;
return interceptor;
}
private static void registryMapperXml ( MybatisConfiguration configuration, String classPath) throws IOException {
ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ;
Enumeration < URL> mapper = contextClassLoader. getResources ( classPath) ;
while ( mapper. hasMoreElements ( ) ) {
URL url = mapper. nextElement ( ) ;
if ( "file" . equals ( url. getProtocol ( ) ) ) {
String path = url. getPath ( ) ;
File file = new File ( path) ;
File [ ] files = file. listFiles ( ) ;
if ( files != null ) {
for ( File f : files) {
FileInputStream in = new FileInputStream ( f) ;
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder ( in, configuration, f. getPath ( ) , configuration. getSqlFragments ( ) ) ;
xmlMapperBuilder. parse ( ) ;
in. close ( ) ;
}
}
} else {
JarURLConnection urlConnection = ( JarURLConnection ) url. openConnection ( ) ;
JarFile jarFile = urlConnection. getJarFile ( ) ;
Enumeration < JarEntry > entries = jarFile. entries ( ) ;
while ( entries. hasMoreElements ( ) ) {
JarEntry jarEntry = entries. nextElement ( ) ;
if ( jarEntry. getName ( ) . endsWith ( ".xml" ) ) {
InputStream in = jarFile. getInputStream ( jarEntry) ;
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder ( in, configuration, jarEntry. getName ( ) , configuration. getSqlFragments ( ) ) ;
xmlMapperBuilder. parse ( ) ;
in. close ( ) ;
}
}
}
}
}
}
2.2、MybatisPlus代码生成器
package com. wxhnyfy ;
import com. alibaba. fastjson2. JSON ;
import com. alibaba. fastjson2. JSONWriter ;
import com. baomidou. mybatisplus. generator. FastAutoGenerator ;
import com. baomidou. mybatisplus. generator. config. * ;
import com. baomidou. mybatisplus. generator. config. builder. Entity ;
import com. baomidou. mybatisplus. generator. config. builder. Mapper ;
import com. baomidou. mybatisplus. generator. config. rules. DbColumnType ;
import com. baomidou. mybatisplus. generator. engine. FreemarkerTemplateEngine ;
import org. slf4j. Logger ;
import org. slf4j. LoggerFactory ;
import java. io. File ;
import java. sql. Types ;
import java. util. ArrayList ;
import java. util. Collections ;
import java. util. List ;
import java. util. function. Consumer ;
public class MybatisPlusGenerator {
private static final Logger logger = LoggerFactory . getLogger ( MybatisPlusGenerator . class ) ;
private static final ProjectConfiguration CONFIGURATION = ProjectConfiguration . getConfiguration ( ) ;
private static String OUTPUT_DIR ;
private static String XML_FILE_OUTPUT_DIR ;
private static void initPath ( ) {
File file = new File ( "1.txt" ) ;
String projectPath = file. getAbsolutePath ( ) . replace ( file. getName ( ) , "" ) ;
String projectName = CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . getProjectName ( ) ;
if ( null != projectName &&
! projectName. isEmpty ( ) ) {
if ( ! projectName. endsWith ( "\\" ) ) {
CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . setProjectName (
projectName + "\\"
) ;
}
projectPath = file. getAbsolutePath ( ) . replace ( file. getName ( ) , "" )
+ CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . getProjectName ( ) ;
}
logger. info ( ">>>> 项目根目录: {}" , projectPath) ;
OUTPUT_DIR = projectPath + CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . getCodeDir ( ) ;
XML_FILE_OUTPUT_DIR = projectPath + CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . getXmlDir ( ) ;
logger. info ( ">>>> java文件输出目录: {}" , OUTPUT_DIR ) ;
logger. info ( ">>>> xml文件输出目录: {}" , XML_FILE_OUTPUT_DIR ) ;
}
private static Consumer < StrategyConfig. Builder > getStrategyConfigBuilder ( List < String > queryList, boolean isGenerateMpjMapper) {
return builder -> {
boolean isGenerateMapperXml = CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . isGenerateMapperXml ( ) ;
boolean isUseDefaultFreemarkerTemplate = CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . isUseDefaultFreemarkerTemplate ( ) ;
boolean isEnableLombok = CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . isEnableLombok ( ) ;
builder. addInclude ( queryList) . controllerBuilder ( ) . disable ( ) . serviceBuilder ( ) . disableService ( ) . disableServiceImpl ( ) . disable ( ) ;
Mapper. Builder mapperBuilder = builder. mapperBuilder ( ) ;
Entity. Builder entityBuilder = builder. entityBuilder ( ) ;
if ( isGenerateMapperXml) {
if ( isGenerateMpjMapper) {
mapperBuilder. enableFileOverride ( ) . mapperTemplate ( "/templates/mapper-mpj.java" ) ;
} else {
mapperBuilder. enableFileOverride ( ) ;
}
} else {
if ( isGenerateMpjMapper) {
mapperBuilder. disableMapperXml ( ) . enableFileOverride ( ) . mapperTemplate ( "/templates/mapper-mpj.java" ) ;
} else {
mapperBuilder. disableMapperXml ( ) . enableFileOverride ( ) ;
}
}
if ( isEnableLombok) {
if ( isUseDefaultFreemarkerTemplate) {
entityBuilder. enableLombok ( ) . enableFileOverride ( ) ;
} else {
entityBuilder. enableLombok ( ) . enableFileOverride ( ) . javaTemplate ( "/templates/entity.java" ) ;
}
} else {
entityBuilder. enableFileOverride ( ) ;
}
} ;
}
private static Consumer < GlobalConfig. Builder > getGlobalConfigBuilder ( ) {
return builder -> {
builder. author ( CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . getAuthor ( ) )
. disableOpenDir ( )
. outputDir ( OUTPUT_DIR ) ;
} ;
}
private static Consumer < DataSourceConfig. Builder > getDataSourceConfigBuilder ( ) {
return builder ->
builder. typeConvertHandler ( ( globalConfig, typeRegistry, metaInfo) -> {
int typeCode = metaInfo. getJdbcType ( ) . TYPE_CODE ;
if ( typeCode == Types . SMALLINT ) {
return DbColumnType . INTEGER ;
}
return typeRegistry. getColumnType ( metaInfo) ;
} ) ;
}
private static Consumer < PackageConfig. Builder > getPackageConfigBuilder ( ) {
return builder ->
builder. parent ( CONFIGURATION . getMybatisPlusConfiguration ( ) . getGenerator ( ) . getParentPackage ( ) )
. entity ( "entity" )
. mapper ( "mapper" )
. pathInfo ( Collections . singletonMap ( OutputFile . xml, XML_FILE_OUTPUT_DIR ) ) ;
}
public static void generatorMybatisPlus ( String . . . tableName) {
initPath ( ) ;
List < String > queryList = new ArrayList < > ( List . of ( tableName) ) ;
logger. info ( ">>>> Mybatis-Plus 代码生成器,本实例只生成实体类和Mapper" ) ;
logger. info ( ">>>> 本次生成的表名:{}" , JSON . toJSONString ( queryList, JSONWriter. Feature. WriteMapNullValue ) ) ;
FastAutoGenerator . create ( CONFIGURATION . getJdbc ( ) . getUrl ( ) , CONFIGURATION . getJdbc ( ) . getUsername ( ) , CONFIGURATION . getJdbc ( ) . getPassword ( ) )
. globalConfig ( getGlobalConfigBuilder ( ) )
. dataSourceConfig ( getDataSourceConfigBuilder ( ) )
. packageConfig ( getPackageConfigBuilder ( ) )
. strategyConfig ( getStrategyConfigBuilder ( queryList, false ) )
. templateEngine ( new FreemarkerTemplateEngine ( ) )
. templateConfig ( template ->
template. disable ( TemplateType . CONTROLLER , TemplateType . SERVICE , TemplateType . SERVICE_IMPL )
)
. execute ( ) ;
logger. info ( ">>>> 成功!!!" ) ;
}
public static void generatorMybatisPlusJoin ( String . . . tableName) {
initPath ( ) ;
List < String > queryList = new ArrayList < > ( List . of ( tableName) ) ;
logger. info ( ">>>> Mybatis-Plus 代码生成器,本实例只生成实体类和Mapper" ) ;
logger. info ( ">>>> 本次生成的表名:{}" , JSON . toJSONString ( queryList, JSONWriter. Feature. WriteMapNullValue ) ) ;
FastAutoGenerator . create ( CONFIGURATION . getJdbc ( ) . getUrl ( ) , CONFIGURATION . getJdbc ( ) . getUsername ( ) , CONFIGURATION . getJdbc ( ) . getPassword ( ) )
. globalConfig ( getGlobalConfigBuilder ( ) )
. dataSourceConfig ( getDataSourceConfigBuilder ( ) )
. packageConfig ( getPackageConfigBuilder ( ) )
. strategyConfig ( getStrategyConfigBuilder ( queryList, true ) )
. templateEngine ( new FreemarkerTemplateEngine ( ) )
. templateConfig ( template ->
template. disable ( TemplateType . CONTROLLER , TemplateType . SERVICE , TemplateType . SERVICE_IMPL )
)
. execute ( ) ;
logger. info ( ">>>> 成功!!!" ) ;
}
}
2.3、获取 config.yml 配置
2.3.1、config.yml
jdbc :
url : jdbc: mysql: //localhost: 3306/region? useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username : root
password : CWCcwy12
driverClassName : com.mysql.cj.jdbc.Driver
mybatisPlusConfiguration :
generator :
author : wxhnyfy
codeDir : src/main/java
xmlDir : src/main/resources/mapper
parentPackage : com.wxhnyfy
generateMapperXml : true
enableLombok : true
useDefaultFreemarkerTemplate : false
projectName : ""
mapperConfiguration :
mapUnderscoreToCamelCase : true
useGeneratedKeys : true
mapperPackage : com.wxhnyfy.mapper
xmlPackage : mapper
2.3.2、项目配置类
package com. wxhnyfy ;
import lombok. AllArgsConstructor ;
import lombok. Getter ;
import lombok. NoArgsConstructor ;
import lombok. Setter ;
import org. apache. commons. io. IOUtils ;
import org. slf4j. Logger ;
import org. slf4j. LoggerFactory ;
import org. yaml. snakeyaml. Yaml ;
import java. io. InputStream ;
import java. nio. charset. StandardCharsets ;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ProjectConfiguration {
private static final Logger logger = LoggerFactory . getLogger ( ProjectConfiguration . class ) ;
private Jdbc jdbc;
private static ProjectConfiguration CONFIGURATION ;
private MybatisPlusConfiguration mybatisPlusConfiguration;
public static ProjectConfiguration getConfiguration ( ) {
if ( null == CONFIGURATION ) {
InputStream input = null ;
try {
input = ProjectConfiguration . class . getResourceAsStream ( "/config.yml" ) ;
if ( input != null ) {
String yamlStr = IOUtils . toString ( input, StandardCharsets . UTF_8 ) ;
logger. debug ( ">>>> 读取配置文件内容:{}" , yamlStr) ;
Yaml yaml = new Yaml ( ) ;
CONFIGURATION = yaml. loadAs ( yamlStr, ProjectConfiguration . class ) ;
}
} catch ( Exception ex) {
logger. error ( ">>>> 读取配置文件出现错误:" , ex) ;
} finally {
if ( input != null ) {
try {
input. close ( ) ;
} catch ( Exception ex) {
logger. error ( ">>>> 读取配置文件出现错误:" , ex) ;
}
}
}
}
return CONFIGURATION ;
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class Jdbc {
private String url;
private String username;
private String password;
private String driverClassName;
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class MybatisPlusConfiguration {
private Generator generator;
private MapperConfiguration mapperConfiguration;
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class Generator {
private boolean generateMapperXml = true ;
private boolean enableLombok = true ;
private boolean useDefaultFreemarkerTemplate = false ;
private String author;
private String codeDir;
private String xmlDir;
private String parentPackage;
private String projectName = "" ;
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class MapperConfiguration {
private boolean mapUnderscoreToCamelCase = false ;
private boolean useGeneratedKeys = false ;
private String mapperPackage;
private String xmlPackage;
}
}
2.4、ftl 模板
2.4.1、实体类
package ${package.Entity};
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.*;
/**
* ${table.comment!} 实体类
*
* @author ${author}
* @since ${date}
*/
@Setter
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
<#if table.convert>
@TableName("${table.name}")
</#if>
public class ${entity} {
<#-- 遍历字段生成属性 -->
<#list table.fields as field>
<#if field.keyFlag>
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#else>
@TableId("${field.name}")
</#if>
<#else>
@TableField("${field.name}")
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
}
2.4.2、Mybatis-Plus Join Mapper 接口
package ${package.Mapper};
import ${package.Entity}.${entity};
import com.github.yulichang.base.MPJBaseMapper;
/**
* ${table.comment!} Mapper 接口
*
* @author ${author}
* @since ${date}
*/
public interface ${table.mapperName} extends MPJBaseMapper<${entity}> {
}
3、测试类
3.1、非线程安全
@Test
public void testSqlSession ( ) {
SqlSession session = GetSqlSession . getMybatisPlusSqlSession ( ) ;
AmapRegionMapper amapRegionMapper = session. getMapper ( AmapRegionMapper . class ) ;
List < AmapRegion > list = amapRegionMapper. selectList ( new Page < > ( 1 , 100 ) ,
new LambdaQueryWrapper < AmapRegion > ( )
. eq ( AmapRegion :: getLevel , "province" )
) ;
for ( AmapRegion amapRegion : list) {
logger. debug ( ">>> {}" , JSON . toJSONString ( amapRegion, JSONWriter. Feature. WriteMapNullValue ) ) ;
}
GetSqlSession . cleanSqlSession ( ) ;
session. commit ( ) ;
session. close ( ) ;
}
3.2、线程安全
@Test
public void testSqlSessionManager ( ) {
SqlSessionManager sqlSessionManager = GetSqlSession . safeMybatisPlusSqlSession ( ) ;
sqlSessionManager. startManagedSession ( true ) ;
AmapRegionMapper amapRegionMapper = sqlSessionManager. getMapper ( AmapRegionMapper . class ) ;
List < AmapRegion > amapRegionList = amapRegionMapper. selectList ( new Page < > ( 1 , 100 ) ,
new LambdaQueryWrapper < AmapRegion > ( )
. eq ( AmapRegion :: getLevel , "province" )
) ;
for ( AmapRegion amapRegion : amapRegionList) {
logger. debug ( ">>> {}" , JSON . toJSONString ( amapRegion, JSONWriter. Feature. WriteMapNullValue ) ) ;
}
GetSqlSession . cleanSqlSessionManager ( ) ;
sqlSessionManager. commit ( ) ;
sqlSessionManager. close ( ) ;
}
3.3、MybatisPlusJoin
@Test
public void testMybatisPlusJoin ( ) {
SqlSessionManager sqlSessionManager = GetSqlSession . safeMybatisPlusJoinSqlSession ( ) ;
sqlSessionManager. startManagedSession ( ) ;
ChinaMcaRegionMapper mapper = sqlSessionManager. getMapper ( ChinaMcaRegionMapper . class ) ;
long total = mapper. selectJoinCount ( new MPJLambdaWrapper < ChinaMcaRegion > ( "l1" )
. leftJoin ( ChinaMcaRegion . class , "l2" , ChinaMcaRegion :: getParentid , "l1" , ChinaMcaRegion :: getId )
. leftJoin ( ChinaMcaRegion . class , "l3" , ChinaMcaRegion :: getParentid , "l2" , ChinaMcaRegion :: getId )
. eq ( "l1.level" , "0" )
. orderBy ( true , true , "l1.code" , "l2.code" , "l3.code" ) ) ;
logger. info ( ">>> total: {}" , total) ;
long pageSize = 200 ;
logger. info ( ">>> pageSize: {}" , pageSize) ;
long pageCount = ( total / pageSize) + ( total % pageSize == 0 ? 0 : 1 ) ;
logger. info ( ">>> pageCount: {}" , pageCount) ;
long pageNum = 8 ;
logger. info ( ">>> pageNum: {}" , pageNum) ;
List < Map < String , Object > > resultPage = mapper. selectJoinMaps ( new MPJLambdaWrapper < ChinaMcaRegion > ( "l1" )
. select ( "IF (( length( `l1`.`code` ) >= 6 ), `l1`.`code`, NULL ) AS `省级行政区编码`" ,
"`l1`.`name` AS `省/自治区/直辖市/特别行政区`" ,
"IF (( length( `l2`.`code` ) >= 6 ), `l2`.`code`, NULL ) AS `地级行政区编码`" ,
"`l2`.`name` AS `地级市/地区/自治州/盟`" ,
"IF (( length( `l3`.`code` ) >= 6 ), `l3`.`code`, NULL ) AS `县级行政区编码`" ,
"`l3`.`name` AS `市辖区/县级市/县/自治县/旗/自治旗/特区/林区`" ,
"( CASE WHEN ( ifnull( `l2`.`name`, '' ) = '' ) THEN " +
"concat( '中国/', `l1`.`name` ) " +
"WHEN ( ifnull( `l3`.`name`, '' ) = '' ) THEN " +
"concat( '中国/', `l1`.`name`, '/', `l2`.`name` ) ELSE concat( '中国/', `l1`.`name`, '/', `l2`.`name`, '/', `l3`.`name` ) " +
"END " +
") AS `全路径名称`" )
. leftJoin ( ChinaMcaRegion . class , "l2" , ChinaMcaRegion :: getParentid , "l1" , ChinaMcaRegion :: getId )
. leftJoin ( ChinaMcaRegion . class , "l3" , ChinaMcaRegion :: getParentid , "l2" , ChinaMcaRegion :: getId )
. eq ( "l1.level" , "0" )
. orderBy ( true , true , "l1.code" , "l2.code" , "l3.code" )
. last ( "limit " + ( pageNum - 1 ) * pageSize + "," + pageSize) ) ;
logger. info ( ">>> resultPage.size(): {}" , resultPage. size ( ) ) ;
for ( Map < String , Object > row : resultPage) {
logger. info ( ">>> {}" , JSON . toJSONString ( row, JSONWriter. Feature. WriteMapNullValue ) ) ;
}
GetSqlSession . cleanSqlSessionManager ( ) ;
sqlSessionManager. commit ( ) ;
sqlSessionManager. close ( ) ;
}
3.4、代码生成器
@Test
public void generatorTable ( ) {
MybatisPlusGenerator . generatorMybatisPlus ( "amap_region" , "baidu_map" ) ;
MybatisPlusGenerator . generatorMybatisPlusJoin ( "china_mca_region" ) ;
}