Commit 21fd52c4 by qiuweili123

数据源开发

parent 9f276ac4
package com.secoo.mall.common.core.classloader;
import com.secoo.mall.common.core.exception.SystemInternalException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class MatrixUrlClassLoader extends URLClassLoader {
private volatile static MatrixUrlClassLoader instance;
private static ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
private static final Method addUrl;
//并行加载classLoader
static {
ClassLoader.registerAsParallelCapable();
}
//初始化添加资源
static {
try {
addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addUrl.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new SystemInternalException();
}
}
public MatrixUrlClassLoader(URL[] urls) {
super(urls);
}
public static MatrixUrlClassLoader getInstance() {
if (instance == null) {
synchronized (MatrixUrlClassLoader.class) {
if (instance == null)
instance = new MatrixUrlClassLoader(new URL[]{});
}
}
return instance;
}
public void loadByUrl(URL url) {
try {
addUrl.invoke(classLoader, url);
} catch (Exception e) {
e.printStackTrace();
throw new SystemInternalException();
}
}
}
# 介绍
mybatis-starter
# 特点
-
# 开始
- 添加依赖
- Maven:需要在自己项目的pom.xml增加,以下配置。
**注意:前置条件需要依赖项目中需要设置matrix的parent**
```xml
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>mybatis-starter</artifactId>
</dependency>
```
# 数据源设计
- core实现由远程加载解密class,根据全局app.id获取加密信息
- starter等组件完成对配置中心、数据源包装
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>matrix-mybatis</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>matrix-mybatis-core</artifactId>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.secoo.mall.mybatis.bean;
import com.secoo.mall.mybatis.config.MatrixDataSourceConfig;
public class MatrixDataSource extends MatrixDataSourceConfig {
}
package com.secoo.mall.mybatis.config;
public interface DataSourceConfig {
/**
* Get the maximum number of milliseconds that a client will wait for a connection from the pool. If this
* time is exceeded without a connection becoming available, a SQLException will be thrown from
* {@link javax.sql.DataSource#getConnection()}.
*
* @return the connection timeout in milliseconds
*/
long getConnectionTimeout();
/**
* Set the maximum number of milliseconds that a client will wait for a connection from the pool. If this
* time is exceeded without a connection becoming available, a SQLException will be thrown from
* {@link javax.sql.DataSource#getConnection()}.
*
* @param connectionTimeoutMs the connection timeout in milliseconds
*/
void setConnectionTimeout(long connectionTimeoutMs);
/**
* This property controls the maximum amount of time (in milliseconds) that a connection is allowed to sit
* idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30
* seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout.
* A value of 0 means that idle connections are never removed from the pool.
*
* @return the idle timeout in milliseconds
*/
long getIdleTimeout();
/**
* This property controls the maximum amount of time (in milliseconds) that a connection is allowed to sit
* idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30
* seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout.
* A value of 0 means that idle connections are never removed from the pool.
*
* @param idleTimeoutMs the idle timeout in milliseconds
*/
void setIdleTimeout(long idleTimeoutMs);
/**
* This property controls the maximum lifetime of a connection in the pool. When a connection reaches this
* timeout, even if recently used, it will be retired from the pool. An in-use connection will never be
* retired, only when it is idle will it be removed.
*
* @return the maximum connection lifetime in milliseconds
*/
long getMaxLifetime();
/**
* This property controls the maximum lifetime of a connection in the pool. When a connection reaches this
* timeout, even if recently used, it will be retired from the pool. An in-use connection will never be
* retired, only when it is idle will it be removed.
*
* @param maxLifetimeMs the maximum connection lifetime in milliseconds
*/
void setMaxLifetime(long maxLifetimeMs);
/**
* The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool,
* including both idle and in-use connections. If the idle connections dip below this value, HikariCP will
* make a best effort to restore them quickly and efficiently.
*
* @return the minimum number of connections in the pool
*/
int getMinimumIdle();
/**
* The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool,
* including both idle and in-use connections. If the idle connections dip below this value, HikariCP will
* make a best effort to restore them quickly and efficiently.
*
* @param minIdle the minimum number of idle connections in the pool to maintain
*/
void setMinimumIdle(int minIdle);
/**
* The property controls the maximum number of connections that HikariCP will keep in the pool,
* including both idle and in-use connections.
*
* @return the maximum number of connections in the pool
*/
int getMaximumPoolSize();
/**
* The property controls the maximum size that the pool is allowed to reach, including both idle and in-use
* connections. Basically this value will determine the maximum number of actual connections to the database
* backend.
* <p>
* When the pool reaches this size, and no idle connections are available, calls to getConnection() will
* block for up to connectionTimeout milliseconds before timing out.
*
* @param maxPoolSize the maximum number of connections in the pool
*/
void setMaximumPoolSize(int maxPoolSize);
/**
* Set the password used for authentication. Changing this at runtime will apply to new connections only.
* Altering this at runtime only works for DataSource-based connections, not Driver-class or JDBC URL-based
* connections.
*
* @param password the database password
*/
void setPassword(String password);
/**
* Set the username used for authentication. Changing this at runtime will apply to new connections only.
* Altering this at runtime only works for DataSource-based connections, not Driver-class or JDBC URL-based
* connections.
*
* @param username the database username
*/
void setUsername(String username);
/**
* The name of the data source.
*
* @return the name of the connection pool
*/
String getName();
}
package com.secoo.mall.mybatis.config;
import com.secoo.mall.mybatis.constants.DataSourceType;
import lombok.Data;
@Data
public class MatrixDataSourceConfig implements DataSourceConfig {
public static final String PREFIX = "spring.datasource.matrix";
/**
* SourceType DRUID or HIKARI.
* Default value HIKARI.
*/
private DataSourceType type;
private String name;
private String username;
private String password;
/**
* Connection url
*/
private String url;
private int minimumIdle;
private int maxPoolSize;
private long connectionTimeout;
private long idleTimeout;
private long maxLifetime;
@Override
public long getConnectionTimeout() {
return connectionTimeout;
}
@Override
public void setConnectionTimeout(long connectionTimeoutMs) {
this.connectionTimeout = connectionTimeoutMs;
}
@Override
public long getIdleTimeout() {
return idleTimeout;
}
@Override
public void setIdleTimeout(long idleTimeoutMs) {
this.idleTimeout = idleTimeoutMs;
}
@Override
public long getMaxLifetime() {
return maxLifetime;
}
@Override
public void setMaxLifetime(long maxLifetimeMs) {
this.maxLifetime = maxLifetimeMs;
}
@Override
public int getMinimumIdle() {
return this.minimumIdle;
}
@Override
public void setMinimumIdle(int minIdle) {
this.minimumIdle = minIdle;
}
@Override
public int getMaximumPoolSize() {
return maxPoolSize;
}
@Override
public void setMaximumPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
}
package com.secoo.mall.mybatis.constants;
public enum DataSourceType {
DRUID,HIKARI;
}
package com.secoo.mall.mybatis.encryptor;
/**
* Encryptor
* @param <T>
*/
public interface Encryptor<T> {
/**
* Encrypt the raw value.
*/
T encrypt(T value);
/**
* Decrypt the encrypted value
*/
T decrypt(T encryptedValue);
}
package com.secoo.mall.mybatis.encryptor;
public class EncryptorFactory {
private static EncryptorFactory instance;
private Encryptor encryptor;
private EncryptorFactory() {
}
public static EncryptorFactory getInstance() {
if (instance == null) {
synchronized (EncryptorFactory.class) {
if (instance == null)
instance = new EncryptorFactory();
}
}
return instance;
}
public Encryptor getEncryptor() {
return null;
}
}
...@@ -3,43 +3,40 @@ ...@@ -3,43 +3,40 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>matrix</artifactId> <artifactId>matrix-mybatis</artifactId>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-starter</artifactId> <artifactId>matrix-mybatis-starter</artifactId>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId> <artifactId>matrix-mybatis-core</artifactId>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-util</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId> <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>com.alibaba</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>druid-spring-boot-starter</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId> <artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-tx</artifactId> <artifactId>spring-boot-starter-aop</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>spring-boot-configuration-processor</artifactId> <artifactId>config-starter</artifactId>
<optional>true</optional>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
...@@ -9,8 +9,8 @@ import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor; ...@@ -9,8 +9,8 @@ import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.baomidou.mybatisplus.extension.toolkit.PackageHelper; import com.baomidou.mybatisplus.extension.toolkit.PackageHelper;
import com.secoo.mall.common.constant.CommonConstant; import com.secoo.mall.common.constant.CommonConstant;
import com.secoo.mall.common.util.string.StringUtil;
import com.secoo.mall.mybatis.handler.FillDefaultValueHandler; import com.secoo.mall.mybatis.handler.FillDefaultValueHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.JdbcType;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
...@@ -40,7 +40,7 @@ public class MybatisConfig { ...@@ -40,7 +40,7 @@ public class MybatisConfig {
String[] aliasesPackages = PackageHelper.convertTypeAliasesPackage("com.secoo.mall.**.bean.domain"); String[] aliasesPackages = PackageHelper.convertTypeAliasesPackage("com.secoo.mall.**.bean.domain");
List<String> list = Stream.of(aliasesPackages).collect(Collectors.toList()); List<String> list = Stream.of(aliasesPackages).collect(Collectors.toList());
/*文件包别名加载*/ /*文件包别名加载*/
sqlSessionFactory.setTypeAliasesPackage(StringUtils.join(list, ",")); sqlSessionFactory.setTypeAliasesPackage(StringUtil.join(list, ","));
/*配置文件*/ /*配置文件*/
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml")); sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
/* 数据源 */ /* 数据源 */
......
package com.secoo.mall.mybatis.spring.boot.autoconfigure;
import com.secoo.mall.mybatis.config.MatrixDataSourceConfig;
import lombok.Data;
//@ConfigurationProperties(prefix = MasterDataSourceProperties.PREFIX)
@Data
public class MasterDataSourceProperties extends MatrixDataSourceConfig {
public static final String PREFIX = MatrixDataSourceConfig.PREFIX+".master";
}
package com.secoo.mall.mybatis.spring.boot.autoconfigure;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.spring.boot.autoconfigure.stat.DruidFilterConfiguration;
import com.alibaba.druid.spring.boot.autoconfigure.stat.DruidSpringAopConfiguration;
import com.alibaba.druid.spring.boot.autoconfigure.stat.DruidStatViewServletConfiguration;
import com.alibaba.druid.spring.boot.autoconfigure.stat.DruidWebStatFilterConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import javax.sql.DataSource;
/*
@Configuration
@ConditionalOnClass(com.alibaba.druid.pool.DruidDataSource.class)
@AutoConfigureBefore(name = {
"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration",
"com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration"
})
@ConditionalOnProperty(prefix = MatrixDataSourceProperties.PREFIX,name = "type", havingValue = "druid", matchIfMissing = false)
@EnableConfigurationProperties({MatrixDataSourceProperties.class,DruidStatProperties.class, DataSourceProperties.class})
@Import({DruidSpringAopConfiguration.class,
DruidStatViewServletConfiguration.class,
DruidWebStatFilterConfiguration.class,
DruidFilterConfiguration.class})*/
@Slf4j
public class MatrixDataSouceAutoConfiguration extends DruidDataSourceAutoConfigure{
public MatrixDataSouceAutoConfiguration(){
log.info("init MatrixDataSouce");
}
}
package com.secoo.mall.mybatis.spring.boot.initializer;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.util.ResourceUtils;
import sun.rmi.runtime.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
public class MybatisApplicationContextInitializer extends ApolloApplicationContextInitializer{
private static Logger log= LoggerFactory.getLogger(MybatisApplicationContextInitializer.class);
public static String MYBATIS_ENCRYPT_PWD = "mybats.encryptor.pwd";
public static String MYBATIS_ENCRYPT_SALT = "mybats.encryptor.salt";
public static String ENCRYPT_FILE_NAME = "encryptor.properties";
@Override
protected void initialize(ConfigurableEnvironment environment) {
super.initialize(environment);
}
// public static Integer ORDER = ApolloApplicationContextInitializer.DEFAULT_ORDER + 100;
/* @Override
public void initialize(ConfigurableApplicationContext context) {
//log.info("initialize.....................");
ConfigurableEnvironment environment = context.getEnvironment();
if (!environment.containsProperty(MYBATIS_ENCRYPT_PWD)) {
Properties properties = new Properties();
//从-D读取
initDConfig(properties);
//从文件加载
initFileConfig(properties);
//解密配置
initApolloConfig(properties);
environment.getPropertySources();
environment.getPropertySources().addFirst((new PropertiesPropertySource("matrixProperties", properties)));
}
}
@Override
public int getOrder() {
return ORDER;
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
// log.info("postProcessEnvironment.......");
}
private void initDConfig(Properties properties) {
if (System.getProperty(MYBATIS_ENCRYPT_PWD) != null) {
properties.setProperty(MYBATIS_ENCRYPT_PWD, System.getProperty(MYBATIS_ENCRYPT_PWD));
properties.setProperty(MYBATIS_ENCRYPT_SALT, System.getProperty(MYBATIS_ENCRYPT_SALT));
}
}
private void initFileConfig(Properties properties) {
if(!properties.containsKey(MYBATIS_ENCRYPT_PWD)) {
try {
File file = ResourceUtils.getFile(SystemUtils.USER_HOME + File.separator + ENCRYPT_FILE_NAME);
if (!file.exists()) {
// log.warn(ENCRYPT_FILE_NAME + " not exist");
return;
}
properties.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*//**
* 解密相关的配置
*//*
private void initApolloConfig(Properties properties){
Config appConfig = ConfigService.getConfig("db.config");
Set<String> propertyNames = appConfig.getPropertyNames();
// log.info(propertyNames.toString());
}*/
}
package com.secoo.mall.mybatis.spring.boot.listener;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
@Slf4j
@NoArgsConstructor
public class MybatisApplicationRunListener implements SpringApplicationRunListener, Ordered {
public static String MYBATIS_ENCRYPT_PWD = "mybats.encryptor.pwd";
public static String MYBATIS_ENCRYPT_SALT = "mybats.encryptor.salt";
public static String ENCRYPT_FILE_NAME = "encryptor.properties";
public static Integer ORDER = ApolloApplicationContextInitializer.DEFAULT_ORDER + 1;
public MybatisApplicationRunListener(SpringApplication application, String[] args) {
}
@Override
public void starting() {
log.info("Appication Starting.....");
}
/**
* 配置加载的依次顺序:
* 1.-spring.config方式加载外部配置
* 2.-D获取
* 3.本地
*
* @param environment
*/
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
if (!environment.containsProperty(MYBATIS_ENCRYPT_PWD)) {
Properties properties = new Properties();
//从-D读取
initDConfig(properties);
//从文件加载
initFileConfig(properties);
//解密配置
// initApolloConfig(properties);
environment.getPropertySources();
environment.getPropertySources().addFirst((new PropertiesPropertySource("matrixProperties", properties)));
}
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
ConfigurableEnvironment environment = context.getEnvironment();
log.info("contextPrepared......");
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
}
@Override
public void started(ConfigurableApplicationContext context) {
}
@Override
public void running(ConfigurableApplicationContext context) {
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
}
@Override
public int getOrder() {
return ORDER;
}
private void initDConfig(Properties properties) {
if (System.getProperty(MYBATIS_ENCRYPT_PWD) != null) {
properties.setProperty(MYBATIS_ENCRYPT_PWD, System.getProperty(MYBATIS_ENCRYPT_PWD));
properties.setProperty(MYBATIS_ENCRYPT_SALT, System.getProperty(MYBATIS_ENCRYPT_SALT));
}
}
private void initFileConfig(Properties properties) {
if(!properties.containsKey(MYBATIS_ENCRYPT_PWD)) {
try {
File file = ResourceUtils.getFile(SystemUtils.USER_HOME + File.separator + ENCRYPT_FILE_NAME);
if (!file.exists()) {
log.warn(ENCRYPT_FILE_NAME + " not exist");
return;
}
properties.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 解密相关的配置
*/
private void initApolloConfig(Properties properties){
Config appConfig = ConfigService.getConfig("db.config");
Set<String> propertyNames = appConfig.getPropertyNames();
log.info(propertyNames.toString());
}
}
com.secoo.mall.mybatis.spring.boot.autoconfigure.MatrixDataSouceAutoConfiguration=
\ No newline at end of file
# Auto Configure
#org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
#com.secoo.mall.mybatis.spring.boot.autoconfigure.MatrixDataSouceAutoConfiguration
org.springframework.context.ApplicationContextInitializer=\
com.secoo.mall.mybatis.spring.boot.initializer.MybatisApplicationContextInitializer
\ No newline at end of file
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>matrix-mybatis</artifactId>
<packaging>pom</packaging>
<modules>
<module>matrix-mybatis-starter</module>
<module>matrix-mybatis-core</module>
</modules>
<properties>
<mybatis-plus.version>3.1.0</mybatis-plus.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mybatis-core</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-mybatis-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-util</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
# 介绍
mybatis-starter基于[mybatis-plus](https://mp.baomidou.com/)进行二次封装,简化对dao层数据访问操作。
# 特点
- 提供分页Page对象统一封装
- 提供分页对象结果DataPage,进行统一定义
- 非生产环境提供sql打印
- 支持createTime默认字段填充(见demo)
- 支持事务切面。增加matrix.aop-transaction.enabled配置,默认false,未开启,此时在需要的事务上增加@Transactional。修改为true,表示service方法名以add、save、create、modify、update、remove、delete为前缀的方法自动追加事务。
# 最佳实践
- matrix.aop-transaction.enabled设置为true,节省事务配置
- bean路径放置com.secoo.mall.**.bean.domain
- xml放置在resource/mybatis路径下
- 对于复杂sql使用xml,如多表关联查询,对于单表操作使用QueryWapper操作
- 所有与数据叫交互放到Mapper中,不要直接写在service中。如
```
@Mapper
public interface ProjectMapper extends BaseMapper<Project> {
default Project getByName(String name) {
return this.selectOne(new QueryWrapper<Project> ().lambda().eq(Project::getName, name).ne(Project::getStatus, ProjectConstant.Status.DELETE).last(" limit 1"));
}
```
# 文档
- [mybaties-plus开发指南](https://mp.baomidou.com/guide/)
# 开始
- 添加依赖
- Maven:需要在自己项目的pom.xml增加,以下配置。
**注意:前置条件需要依赖项目中需要设置matrix的parent**
```xml
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>mybatis-starter</artifactId>
</dependency>
```
# 示例
- Bean自动填充字段 @TableField
```
public class Project extends AbsBaseBean {
......
@ApiModelProperty(value = "创建时间", hidden = true)
@TableField(fill = FieldFill.INSERT)
private Date createTime;
.....
}
```
- 分页工具类PageUtil使用
- ProjectController
```
@ApiOperation(value = "应用多属性查询", notes = "应用多属性查询")
@PostMapping("/search")
public Object search(Project project, ReqPage reqPage, Sort sort) {
Page<Project> page = PageUtil.createPage(reqPage, sort);
return service.search(project, page);
}
```
- ProjectService
```
public DataPage<Project> search(Project project, Page<Project> page) {
IPage<Project> iPage = mapper.search(project, page);
return PageUtil.createDataPage(iPage);
}
```
- 访问方式
http://localhost:8080/doc.html切换为web可以进行调试
\ No newline at end of file
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>matrix</artifactId> <artifactId>matrix</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
<module>common-core</module> <module>common-core</module>
<module>common-util</module> <module>common-util</module>
<module>redis-starter</module> <module>redis-starter</module>
<module>mybatis-starter</module> <module>matrix-mybatis</module>
<module>mongodb-starter</module> <module>mongodb-starter</module>
<module>elasticsearch-starter</module> <module>elasticsearch-starter</module>
<module>openfeign-starter</module> <module>openfeign-starter</module>
...@@ -40,7 +40,7 @@ ...@@ -40,7 +40,7 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId> <artifactId>spring-boot-dependencies</artifactId>
<version>2.2.1.RELEASE</version> <version>2.1.9.RELEASE</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
...@@ -48,62 +48,62 @@ ...@@ -48,62 +48,62 @@
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>logger-starter</artifactId> <artifactId>logger-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>monitor-starter</artifactId> <artifactId>monitor-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId> <artifactId>common-core</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>config-starter</artifactId> <artifactId>config-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>common-util</artifactId> <artifactId>common-util</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>redis-starter</artifactId> <artifactId>redis-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>mybatis-starter</artifactId> <artifactId>matrix-mybatis-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>mongodb-starter</artifactId> <artifactId>mongodb-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>elasticsearch-starter</artifactId> <artifactId>elasticsearch-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>protocol-starter</artifactId> <artifactId>protocol-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>rocketmq-starter</artifactId> <artifactId>rocketmq-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.secoo.mall</groupId> <groupId>com.secoo.mall</groupId>
<artifactId>openfeign-starter</artifactId> <artifactId>openfeign-starter</artifactId>
<version>1.1.8.RELEASE</version> <version>1.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
...@@ -153,22 +153,6 @@ ...@@ -153,22 +153,6 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>20.0</version> <version>20.0</version>
...@@ -281,14 +265,6 @@ ...@@ -281,14 +265,6 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<version>2.2.0.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment