commit
a63143aeb0
@ -0,0 +1,28 @@ |
||||
# Created by .ignore support plugin (hsz.mobi) |
||||
### Java template |
||||
# Compiled class file |
||||
*.class |
||||
|
||||
# Log file |
||||
*.log |
||||
|
||||
# BlueJ files |
||||
*.ctxt |
||||
|
||||
# Mobile Tools for Java (J2ME) |
||||
.mtj.tmp/ |
||||
|
||||
# Package Files # |
||||
*.jar |
||||
*.war |
||||
*.nar |
||||
*.ear |
||||
*.zip |
||||
*.tar.gz |
||||
*.rar |
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml |
||||
hs_err_pid* |
||||
|
||||
/.idea/ |
||||
*.iml |
@ -0,0 +1,96 @@ |
||||
<?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"> |
||||
<modelVersion>4.0.0</modelVersion> |
||||
|
||||
<groupId>org.pqh</groupId> |
||||
<artifactId>hibernate</artifactId> |
||||
<version>1.0-SNAPSHOT</version> |
||||
|
||||
<properties> |
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> |
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> |
||||
<java.version>1.8</java.version> |
||||
|
||||
<hibernate-core.version>5.4.2.Final</hibernate-core.version> |
||||
<spring.version>5.1.6.RELEASE</spring.version> |
||||
<log4j.version>2.11.2</log4j.version> |
||||
<druid.version>1.1.15</druid.version> |
||||
<commons-lang3.version>3.8.1</commons-lang3.version> |
||||
<commons-io.version>2.6</commons-io.version> |
||||
<mysql.version>8.0.15</mysql.version> |
||||
<fastjson.version>1.2.56</fastjson.version> |
||||
</properties> |
||||
|
||||
<dependencies> |
||||
<dependency> |
||||
<groupId>org.hibernate</groupId> |
||||
<artifactId>hibernate-core</artifactId> |
||||
<version>${hibernate-core.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>mysql</groupId> |
||||
<artifactId>mysql-connector-java</artifactId> |
||||
<version>${mysql.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.springframework</groupId> |
||||
<artifactId>spring-orm</artifactId> |
||||
<version>${spring.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.springframework</groupId> |
||||
<artifactId>spring-context</artifactId> |
||||
<version>${spring.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.apache.logging.log4j</groupId> |
||||
<artifactId>log4j-web</artifactId> |
||||
<version>${log4j.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>com.alibaba</groupId> |
||||
<artifactId>druid</artifactId> |
||||
<version>${druid.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.apache.commons</groupId> |
||||
<artifactId>commons-lang3</artifactId> |
||||
<version>${commons-lang3.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>commons-io</groupId> |
||||
<artifactId>commons-io</artifactId> |
||||
<version>${commons-io.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>com.alibaba</groupId> |
||||
<artifactId>fastjson</artifactId> |
||||
<version>${fastjson.version}</version> |
||||
</dependency> |
||||
</dependencies> |
||||
|
||||
<build> |
||||
<plugins> |
||||
<plugin> |
||||
<groupId>org.apache.maven.plugins</groupId> |
||||
<artifactId>maven-compiler-plugin</artifactId> |
||||
<version>3.6.1</version> |
||||
<configuration> |
||||
<source>${java.version}</source> |
||||
<target>${java.version}</target> |
||||
<encoding>${project.build.sourceEncoding}</encoding> |
||||
</configuration> |
||||
</plugin> |
||||
</plugins> |
||||
</build> |
||||
</project> |
@ -0,0 +1,16 @@ |
||||
package annotation; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Target({ElementType.TYPE}) |
||||
/** |
||||
* 表备注信息 |
||||
*/ |
||||
public @interface TableInfo { |
||||
//表别名
|
||||
String comment(); |
||||
} |
@ -0,0 +1,57 @@ |
||||
package config; |
||||
|
||||
import model.AbstractModel; |
||||
import org.hibernate.criterion.DetachedCriteria; |
||||
import org.hibernate.criterion.Projections; |
||||
import org.springframework.dao.DataAccessException; |
||||
import org.springframework.orm.hibernate5.HibernateTemplate; |
||||
|
||||
import java.io.Serializable; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* Created by reborn on 2017/7/28. |
||||
*/ |
||||
|
||||
public abstract class BaseService { |
||||
|
||||
public abstract HibernateTemplate getHibernateTemplate(); |
||||
|
||||
public <T extends AbstractModel> Serializable save(T command) throws DataAccessException { |
||||
return getHibernateTemplate().save(command); |
||||
} |
||||
|
||||
public <T extends AbstractModel> void update(T command) throws DataAccessException{ |
||||
getHibernateTemplate().update(command); |
||||
} |
||||
|
||||
public final <T extends AbstractModel> T get(T command) throws DataAccessException { |
||||
return (T) getHibernateTemplate().get((Class<T>)(command.getClass()), command.primaryKey()); |
||||
} |
||||
|
||||
public <T extends AbstractModel> void delete(T command) throws DataAccessException{ |
||||
T model=get(command); |
||||
if(model!=null){ |
||||
getHibernateTemplate().delete(model); |
||||
} |
||||
} |
||||
|
||||
public final List find(DetachedCriteria criteria, int firstResult,int maxResults) throws DataAccessException{ |
||||
return getHibernateTemplate().findByCriteria(criteria,firstResult,maxResults); |
||||
} |
||||
|
||||
public final List find(DetachedCriteria criteria) throws DataAccessException{ |
||||
return getHibernateTemplate().findByCriteria(criteria); |
||||
} |
||||
|
||||
/** |
||||
* 根据查询条件统计记录数 |
||||
* @param criteria |
||||
* @return |
||||
*/ |
||||
public Long rowCount(DetachedCriteria criteria){ |
||||
return getHibernateTemplate().executeWithNativeSession(session -> (Long) criteria.setProjection(Projections.rowCount()).getExecutableCriteria(session).uniqueResult()); |
||||
} |
||||
|
||||
|
||||
} |
@ -0,0 +1,35 @@ |
||||
package config; |
||||
|
||||
import org.hibernate.dialect.Dialect; |
||||
import org.hibernate.dialect.MySQL57Dialect; |
||||
|
||||
import java.sql.Driver; |
||||
|
||||
public enum DBType{ |
||||
mysql57(com.mysql.cj.jdbc.Driver.class, MySQL57Dialect.class); |
||||
|
||||
private Class<? extends Driver> driver; |
||||
private Class<? extends Dialect> dialect; |
||||
|
||||
DBType(Class<? extends Driver> driver, Class<? extends Dialect> dialect) { |
||||
this.driver = driver; |
||||
this.dialect = dialect; |
||||
} |
||||
|
||||
public Class<? extends Driver> getDriver() { |
||||
return driver; |
||||
} |
||||
|
||||
public Class<? extends Dialect> getDialect() { |
||||
return dialect; |
||||
} |
||||
|
||||
public String getUrl(String host,int port,String name){ |
||||
switch (DBType.valueOf(this.name())){ |
||||
case mysql57: return "jdbc:mysql://" + host + ":" + port + "/" + name + "?serverTimezone=GMT%2b8"; |
||||
default:throw new RuntimeException("NotFound type:"+this.name()); |
||||
} |
||||
} |
||||
|
||||
|
||||
} |
@ -0,0 +1,170 @@ |
||||
package config; |
||||
|
||||
import annotation.TableInfo; |
||||
import com.alibaba.druid.pool.DruidDataSource; |
||||
import com.alibaba.fastjson.JSON; |
||||
import com.alibaba.fastjson.TypeReference; |
||||
import model.DataSourceModel; |
||||
import org.apache.commons.io.FileUtils; |
||||
import org.apache.commons.lang3.StringUtils; |
||||
import org.hibernate.SessionFactory; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory; |
||||
import org.springframework.core.type.filter.AnnotationTypeFilter; |
||||
import org.springframework.orm.hibernate5.HibernateTemplate; |
||||
import org.springframework.orm.hibernate5.HibernateTransactionManager; |
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean; |
||||
import org.springframework.util.ResourceUtils; |
||||
|
||||
import javax.sql.DataSource; |
||||
import java.io.IOException; |
||||
import java.lang.annotation.Annotation; |
||||
import java.util.HashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
import java.util.Properties; |
||||
|
||||
/** |
||||
* Created by reborn on 2017/7/28. |
||||
*/ |
||||
public class HibernateConfig extends InitConfig { |
||||
|
||||
private static final String CONFIG_NAME = "classpath:database.json"; |
||||
|
||||
@Autowired |
||||
private DefaultListableBeanFactory beanFactory; |
||||
|
||||
private static final Map<Class, TableInfo> tableNotes = new HashMap<>(); |
||||
|
||||
public static TableInfo getTableNote(Class c) { |
||||
return tableNotes.get(c); |
||||
} |
||||
|
||||
private static final Map<Class<? extends Annotation>, SessionFactory> map = new HashMap<>(); |
||||
|
||||
public static SessionFactory get(Class<? extends Annotation> c) { |
||||
return map.get(c); |
||||
} |
||||
|
||||
/** |
||||
* 注册数据源 |
||||
* |
||||
* @param dbName 数据库名 |
||||
* @param dbPort 端口 |
||||
* @param username 用户名 |
||||
* @param password 密码 |
||||
* @param type 数据库类型 |
||||
* @return |
||||
*/ |
||||
private DruidDataSource dataSource(String dbHost, String dbName, int dbPort, String username, String password, DBType type) { |
||||
DruidDataSource dataSource = new DruidDataSource(); |
||||
dataSource.setUsername(username); |
||||
dataSource.setPassword(password); |
||||
String url = ""; |
||||
switch (type) { |
||||
case mysql57: |
||||
url = type.getUrl(dbHost, dbPort, dbName); |
||||
dataSource.setUrl(url); |
||||
dataSource.setDriverClassName(type.getDriver().getName()); |
||||
break; |
||||
} |
||||
LOG.info("数据源初始化\nurl=" + url + "\nusername=" + username + "\npassword=" + password); |
||||
return dataSource; |
||||
} |
||||
|
||||
private DruidDataSource dataSource(DataSourceModel dataSourceModel) { |
||||
return dataSource(dataSourceModel.getHost(), dataSourceModel.getDbName(), dataSourceModel.getPort(), dataSourceModel.getUsername(), dataSourceModel.getPassword(), dataSourceModel.getDbType()); |
||||
} |
||||
|
||||
/** |
||||
* 初始化数据源 |
||||
* |
||||
* @param dataSourceModel |
||||
* @return |
||||
*/ |
||||
private HibernateTemplate initDB(DataSourceModel dataSourceModel) throws IOException { |
||||
DruidDataSource dataSource = dataSource(dataSourceModel); |
||||
SessionFactory sessionFactory = initSessionFactory(dataSource, (LocalSessionFactoryBean bean) -> { |
||||
//按照注解标记从指定包扫描实体类,并且注册到session工厂
|
||||
bean.setPackagesToScan(dataSourceModel.getPackagesToScan()); |
||||
bean.setEntityTypeFilters(new AnnotationTypeFilter(dataSourceModel.getAnnotation())); |
||||
}, dataSourceModel.getDbName(), dataSourceModel.getDbType().getDialect().getName()); |
||||
|
||||
beanFactory.registerSingleton(dataSourceModel.getSessionFactoryBean(), sessionFactory); |
||||
if (sessionFactory != null) { |
||||
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager(); |
||||
hibernateTransactionManager.setSessionFactory(sessionFactory); |
||||
hibernateTransactionManager.setDataSource(dataSource); |
||||
hibernateTransactionManager.afterPropertiesSet(); |
||||
//添加事务管理器
|
||||
beanFactory.registerSingleton(dataSourceModel.getTransactionManagerBean(), hibernateTransactionManager); |
||||
return new HibernateTemplate(sessionFactory); |
||||
} else { |
||||
throw new RuntimeException("sessionFactory is Null"); |
||||
} |
||||
} |
||||
|
||||
|
||||
/** |
||||
* 初始化数据源,session工厂 |
||||
*/ |
||||
private void init() { |
||||
|
||||
//从根数据源读取其他数据源信息,并初始化
|
||||
List<DataSourceModel> dataSourceModels; |
||||
try { |
||||
dataSourceModels = JSON.parseObject(FileUtils.readFileToString(ResourceUtils.getFile(CONFIG_NAME), "UTF-8"), new TypeReference<List<DataSourceModel>>() { |
||||
}); |
||||
} catch (IOException e) { |
||||
LOG.error("解析数据库配置失败"); |
||||
throw new RuntimeException(e); |
||||
} |
||||
|
||||
if (dataSourceModels.size() == 0) { |
||||
throw new RuntimeException("没有配置数据源,初始化失败"); |
||||
} |
||||
dataSourceModels.forEach(dataSourceModel -> { |
||||
if (map.containsKey(dataSourceModel.getAnnotation())) { |
||||
throw new RuntimeException("数据库配置无效,注解" + dataSourceModel.getAnnotation() + "已重复"); |
||||
} |
||||
HibernateTemplate hibernateTemplate; |
||||
try { |
||||
hibernateTemplate = initDB(dataSourceModel); |
||||
beanFactory.registerSingleton(dataSourceModel.getHibernateBean(), hibernateTemplate); |
||||
map.put(dataSourceModel.getAnnotation(), hibernateTemplate.getSessionFactory()); |
||||
} catch (IOException e) { |
||||
LOG.error("无法获取HibernateTemplate"); |
||||
throw new RuntimeException(e); |
||||
} |
||||
}); |
||||
} |
||||
|
||||
/** |
||||
* 初始化session工厂 |
||||
* |
||||
* @param dataSource |
||||
* @param config |
||||
* @return |
||||
*/ |
||||
private SessionFactory initSessionFactory(DataSource dataSource, SessionFactoryConfig config, String defaultSchema, String dialect) throws IOException { |
||||
LocalSessionFactoryBean bean = new LocalSessionFactoryBean(); |
||||
Properties properties = new Properties(); |
||||
properties.setProperty("hibernate.dialect", dialect); |
||||
properties.setProperty("hibernate.format_sql", "true"); |
||||
if (StringUtils.isNotEmpty(defaultSchema)) { |
||||
properties.setProperty("hibernate.default_schema", defaultSchema); |
||||
} |
||||
bean.setHibernateProperties(properties); |
||||
bean.setDataSource(dataSource); |
||||
config.call(bean); |
||||
bean.afterPropertiesSet(); |
||||
return bean.getObject(); |
||||
} |
||||
|
||||
|
||||
@Override |
||||
public void afterPropertiesSet() throws Exception { |
||||
super.afterPropertiesSet(); |
||||
init(); |
||||
} |
||||
} |
@ -0,0 +1,16 @@ |
||||
package config; |
||||
|
||||
|
||||
import org.apache.logging.log4j.LogManager; |
||||
import org.apache.logging.log4j.Logger; |
||||
import org.springframework.beans.factory.InitializingBean; |
||||
import org.springframework.util.ClassUtils; |
||||
|
||||
public class InitConfig implements InitializingBean { |
||||
public static final Logger LOG = LogManager.getLogger(); |
||||
|
||||
@Override |
||||
public void afterPropertiesSet() throws Exception { |
||||
LOG.info("初始化"+ ClassUtils.getUserClass(this.getClass())+"配置"); |
||||
} |
||||
} |
@ -0,0 +1,9 @@ |
||||
package config; |
||||
|
||||
import model.DataSourceModel; |
||||
|
||||
import java.util.List; |
||||
|
||||
public interface ParseDataSource { |
||||
List<DataSourceModel> parse(); |
||||
} |
@ -0,0 +1,10 @@ |
||||
package config; |
||||
|
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean; |
||||
|
||||
/** |
||||
* 每个工厂有个性化配置单独封装一个回调函数 |
||||
*/ |
||||
public interface SessionFactoryConfig { |
||||
void call(LocalSessionFactoryBean bean); |
||||
} |
@ -0,0 +1,18 @@ |
||||
package model; |
||||
|
||||
import com.alibaba.fastjson.JSON; |
||||
|
||||
import java.io.Serializable; |
||||
|
||||
/** |
||||
* Created by reborn on 2017/8/3. |
||||
*/ |
||||
|
||||
public abstract class AbstractModel{ |
||||
|
||||
public abstract Serializable primaryKey(); |
||||
|
||||
public String toJSON(){ |
||||
return JSON.toJSONString(this); |
||||
} |
||||
} |
@ -0,0 +1,129 @@ |
||||
package model; |
||||
|
||||
import com.alibaba.fastjson.annotation.JSONField; |
||||
import config.DBType; |
||||
|
||||
import java.lang.annotation.Annotation; |
||||
|
||||
public class DataSourceModel { |
||||
private String host; |
||||
private int port; |
||||
private String username; |
||||
private String password; |
||||
private String dbName; |
||||
private DBType dbType; |
||||
private String dbDesc; |
||||
private Class<? extends Annotation> annotation; |
||||
private String sessionFactoryBean; |
||||
private String hibernateBean; |
||||
private String transactionManagerBean; |
||||
private String packagesToScan[]; |
||||
|
||||
@JSONField |
||||
public String getHost() { |
||||
return host; |
||||
} |
||||
|
||||
public void setHost(String host) { |
||||
this.host = host; |
||||
} |
||||
|
||||
@JSONField |
||||
public int getPort() { |
||||
return port; |
||||
} |
||||
|
||||
public void setPort(int port) { |
||||
this.port = port; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getUsername() { |
||||
return username; |
||||
} |
||||
|
||||
public void setUsername(String username) { |
||||
this.username = username; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getPassword() { |
||||
return password; |
||||
} |
||||
|
||||
public void setPassword(String password) { |
||||
this.password = password; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getDbName() { |
||||
return dbName; |
||||
} |
||||
|
||||
public void setDbName(String dbName) { |
||||
this.dbName = dbName; |
||||
} |
||||
|
||||
@JSONField |
||||
public DBType getDbType() { |
||||
return dbType; |
||||
} |
||||
|
||||
public void setDbType(DBType dbType) { |
||||
this.dbType = dbType; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getDbDesc() { |
||||
return dbDesc; |
||||
} |
||||
|
||||
public void setDbDesc(String dbDesc) { |
||||
this.dbDesc = dbDesc; |
||||
} |
||||
|
||||
@JSONField |
||||
public Class<? extends Annotation> getAnnotation() { |
||||
return annotation; |
||||
} |
||||
|
||||
public void setAnnotation(Class<? extends Annotation> annotation) { |
||||
this.annotation = annotation; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getSessionFactoryBean() { |
||||
return sessionFactoryBean; |
||||
} |
||||
|
||||
public void setSessionFactoryBean(String sessionFactoryBean) { |
||||
this.sessionFactoryBean = sessionFactoryBean; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getHibernateBean() { |
||||
return hibernateBean; |
||||
} |
||||
|
||||
public void setHibernateBean(String hibernateBean) { |
||||
this.hibernateBean = hibernateBean; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getTransactionManagerBean() { |
||||
return transactionManagerBean; |
||||
} |
||||
|
||||
public void setTransactionManagerBean(String transactionManagerBean) { |
||||
this.transactionManagerBean = transactionManagerBean; |
||||
} |
||||
|
||||
@JSONField |
||||
public String[] getPackagesToScan() { |
||||
return packagesToScan; |
||||
} |
||||
|
||||
public void setPackagesToScan(String... packagesToScan) { |
||||
this.packagesToScan = packagesToScan; |
||||
} |
||||
} |
@ -0,0 +1,95 @@ |
||||
<?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"> |
||||
<modelVersion>4.0.0</modelVersion> |
||||
|
||||
<groupId>org.pqh</groupId> |
||||
<artifactId>mybatis</artifactId> |
||||
<version>1.0-SNAPSHOT</version> |
||||
|
||||
<properties> |
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> |
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> |
||||
<java.version>1.8</java.version> |
||||
<mysql.version>8.0.15</mysql.version> |
||||
<mybatis-spring.version>2.0.1</mybatis-spring.version> |
||||
<fastjson.version>1.2.56</fastjson.version> |
||||
<log4j.version>2.11.2</log4j.version> |
||||
<druid.version>1.1.15</druid.version> |
||||
<spring.version>5.1.6.RELEASE</spring.version> |
||||
<commons-io.version>2.6</commons-io.version> |
||||
<mybatis.version>3.5.1</mybatis.version> |
||||
</properties> |
||||
|
||||
<dependencies> |
||||
<dependency> |
||||
<groupId>org.springframework</groupId> |
||||
<artifactId>spring-orm</artifactId> |
||||
<version>${spring.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.springframework</groupId> |
||||
<artifactId>spring-context</artifactId> |
||||
<version>${spring.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>mysql</groupId> |
||||
<artifactId>mysql-connector-java</artifactId> |
||||
<version>${mysql.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.mybatis</groupId> |
||||
<artifactId>mybatis</artifactId> |
||||
<version>${mybatis.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.mybatis</groupId> |
||||
<artifactId>mybatis-spring</artifactId> |
||||
<version>${mybatis-spring.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>org.apache.logging.log4j</groupId> |
||||
<artifactId>log4j-web</artifactId> |
||||
<version>${log4j.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>com.alibaba</groupId> |
||||
<artifactId>druid</artifactId> |
||||
<version>${druid.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>com.alibaba</groupId> |
||||
<artifactId>fastjson</artifactId> |
||||
<version>${fastjson.version}</version> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>commons-io</groupId> |
||||
<artifactId>commons-io</artifactId> |
||||
<version>${commons-io.version}</version> |
||||
</dependency> |
||||
</dependencies> |
||||
|
||||
<build> |
||||
<plugins> |
||||
<plugin> |
||||
<groupId>org.apache.maven.plugins</groupId> |
||||
<artifactId>maven-compiler-plugin</artifactId> |
||||
<version>3.6.1</version> |
||||
<configuration> |
||||
<source>${java.version}</source> |
||||
<target>${java.version}</target> |
||||
<encoding>${project.build.sourceEncoding}</encoding> |
||||
</configuration> |
||||
</plugin> |
||||
</plugins> |
||||
</build> |
||||
</project> |
@ -0,0 +1,24 @@ |
||||
package config; |
||||
|
||||
import java.sql.Driver; |
||||
|
||||
public enum DBType { |
||||
mysql57(com.mysql.cj.jdbc.Driver.class); |
||||
|
||||
private Class<? extends Driver> driver; |
||||
|
||||
DBType(Class<? extends Driver> driver) { |
||||
this.driver = driver; |
||||
} |
||||
|
||||
public Class<? extends Driver> getDriver() { |
||||
return driver; |
||||
} |
||||
|
||||
public String getUrl(String host,int port,String name){ |
||||
switch (DBType.valueOf(this.name())){ |
||||
case mysql57: return "jdbc:mysql://" + host + ":" + port + "/" + name + "?serverTimezone=GMT%2b8"; |
||||
default:throw new RuntimeException("NotFound type:"+this.name()); |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,16 @@ |
||||
package config; |
||||
|
||||
|
||||
import org.apache.logging.log4j.LogManager; |
||||
import org.apache.logging.log4j.Logger; |
||||
import org.springframework.beans.factory.InitializingBean; |
||||
import org.springframework.util.ClassUtils; |
||||
|
||||
public class InitConfig implements InitializingBean { |
||||
public static final Logger LOG = LogManager.getLogger(); |
||||
|
||||
@Override |
||||
public void afterPropertiesSet() throws Exception { |
||||
LOG.info("初始化"+ ClassUtils.getUserClass(this.getClass())+"配置"); |
||||
} |
||||
} |
@ -0,0 +1,107 @@ |
||||
package config; |
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource; |
||||
import com.alibaba.fastjson.JSON; |
||||
import com.alibaba.fastjson.TypeReference; |
||||
import model.DataSourceModel; |
||||
import org.apache.commons.io.FileUtils; |
||||
import org.apache.ibatis.session.Configuration; |
||||
import org.mybatis.spring.SqlSessionFactoryBean; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory; |
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver; |
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager; |
||||
import org.springframework.util.ResourceUtils; |
||||
|
||||
import javax.sql.DataSource; |
||||
import java.io.IOException; |
||||
import java.util.List; |
||||
|
||||
public class MyBatisConfig extends InitConfig { |
||||
private static final String CONFIG_NAME = "classpath:database.json"; |
||||
|
||||
@Autowired |
||||
private DefaultListableBeanFactory beanFactory; |
||||
|
||||
/** |
||||
* 注册数据源 |
||||
* |
||||
* @param dbName 数据库名 |
||||
* @param dbPort 端口 |
||||
* @param username 用户名 |
||||
* @param password 密码 |
||||
* @param type 数据库类型 |
||||
* @return |
||||
*/ |
||||
private DruidDataSource dataSource(String dbHost, String dbName, int dbPort, String username, String password, DBType type) { |
||||
DruidDataSource dataSource = new DruidDataSource(); |
||||
dataSource.setUsername(username); |
||||
dataSource.setPassword(password); |
||||
String url = ""; |
||||
switch (type) { |
||||
case mysql57: |
||||
url = type.getUrl(dbHost, dbPort, dbName); |
||||
dataSource.setUrl(url); |
||||
dataSource.setDriverClassName(type.getDriver().getName()); |
||||
break; |
||||
} |
||||
LOG.info("数据源初始化\nurl=" + url + "\nusername=" + username + "\npassword=" + password); |
||||
return dataSource; |
||||
} |
||||
|
||||
private DruidDataSource dataSource(DataSourceModel dataSourceModel) { |
||||
return dataSource(dataSourceModel.getHost(), dataSourceModel.getDbName(), dataSourceModel.getPort(), dataSourceModel.getUsername(), dataSourceModel.getPassword(), dataSourceModel.getDbType()); |
||||
} |
||||
|
||||
private void init() { |
||||
|
||||
//从根数据源读取其他数据源信息,并初始化
|
||||
List<DataSourceModel> dataSourceModels; |
||||
try { |
||||
dataSourceModels = JSON.parseObject(FileUtils.readFileToString(ResourceUtils.getFile(CONFIG_NAME), "UTF-8"), new TypeReference<List<DataSourceModel>>() { |
||||
}); |
||||
} catch (IOException e) { |
||||
LOG.error("解析数据库配置失败"); |
||||
throw new RuntimeException(e); |
||||
} |
||||
|
||||
dataSourceModels.forEach(dataSourceModel -> { |
||||
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); |
||||
DataSource dataSource=dataSource(dataSourceModel); |
||||
factoryBean.setDataSource(dataSource); |
||||
|
||||
DataSourceTransactionManager transactionManager=new DataSourceTransactionManager(); |
||||
transactionManager.setDataSource(dataSource); |
||||
beanFactory.registerSingleton(dataSourceModel.getTransactionManagerBean(), transactionManager); |
||||
|
||||
Configuration configuration = new Configuration(); |
||||
PathMatchingResourcePatternResolver resolver=new PathMatchingResourcePatternResolver(); |
||||
try { |
||||
String path="classpath*:/"+dataSourceModel.getPackageName().replaceAll("\\.","/")+"/*.xml"; |
||||
LOG.info("Mapper匹配规则"+path); |
||||
factoryBean.setMapperLocations(resolver.getResources(path)); |
||||
} catch (IOException e) { |
||||
throw new RuntimeException("mapper匹配规则解析出错"); |
||||
} |
||||
factoryBean.setConfiguration(configuration); |
||||
try { |
||||
if(factoryBean.getObject()!=null){ |
||||
beanFactory.registerSingleton(dataSourceModel.getFactoryBean(), factoryBean.getObject()); |
||||
}else{ |
||||
LOG.error("初始化数据库配置" + JSON.toJSONString(dataSourceModel) + "失败"); |
||||
} |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
throw new RuntimeException("初始化数据库配置" + JSON.toJSONString(dataSourceModel) + "失败"); |
||||
} |
||||
}); |
||||
|
||||
|
||||
} |
||||
|
||||
@Override |
||||
public void afterPropertiesSet() throws Exception { |
||||
super.afterPropertiesSet(); |
||||
init(); |
||||
} |
||||
} |
@ -0,0 +1,107 @@ |
||||
package model; |
||||
|
||||
import com.alibaba.fastjson.annotation.JSONField; |
||||
import config.DBType; |
||||
|
||||
public class DataSourceModel { |
||||
private String host; |
||||
private int port; |
||||
private String username; |
||||
private String password; |
||||
private String dbName; |
||||
private String dbDesc; |
||||
private DBType dbType; |
||||
private String factoryBean; |
||||
private String packageName; |
||||
private String transactionManagerBean; |
||||
|
||||
@JSONField |
||||
public String getHost() { |
||||
return host; |
||||
} |
||||
|
||||
public void setHost(String host) { |
||||
this.host = host; |
||||
} |
||||
|
||||
@JSONField |
||||
public int getPort() { |
||||
return port; |
||||
} |
||||
|
||||
public void setPort(int port) { |
||||
this.port = port; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getUsername() { |
||||
return username; |
||||
} |
||||
|
||||
public void setUsername(String username) { |
||||
this.username = username; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getPassword() { |
||||
return password; |
||||
} |
||||
|
||||
public void setPassword(String password) { |
||||
this.password = password; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getDbName() { |
||||
return dbName; |
||||
} |
||||
|
||||
public void setDbName(String dbName) { |
||||
this.dbName = dbName; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getDbDesc() { |
||||
return dbDesc; |
||||
} |
||||
|
||||
public void setDbDesc(String dbDesc) { |
||||
this.dbDesc = dbDesc; |
||||
} |
||||
|
||||
@JSONField |
||||
public DBType getDbType() { |
||||
return dbType; |
||||
} |
||||
|
||||
public void setDbType(DBType dbType) { |
||||
this.dbType = dbType; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getFactoryBean() { |
||||
return factoryBean; |
||||
} |
||||
|
||||
public void setFactoryBean(String factoryBean) { |
||||
this.factoryBean = factoryBean; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getPackageName() { |
||||
return packageName; |
||||
} |
||||
|
||||
public void setPackageName(String packageName) { |
||||
this.packageName = packageName; |
||||
} |
||||
|
||||
@JSONField |
||||
public String getTransactionManagerBean() { |
||||
return transactionManagerBean; |
||||
} |
||||
|
||||
public void setTransactionManagerBean(String transactionManagerBean) { |
||||
this.transactionManagerBean = transactionManagerBean; |
||||
} |
||||
} |
Loading…
Reference in new issue