[opt] optimize custom table prefix logic

This commit is contained in:
tjq 2020-07-19 22:39:32 +08:00
parent 514e7aad7d
commit 987c016e24
4 changed files with 14 additions and 120 deletions

View File

@ -1,9 +1,6 @@
package com.github.kfcfans.powerjob.server.persistence.config; package com.github.kfcfans.powerjob.server.persistence.config;
import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties; import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings; import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
@ -18,8 +15,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
@ -44,9 +39,6 @@ public class CoreJpaConfig {
@Resource(name = "omsCoreDatasource") @Resource(name = "omsCoreDatasource")
private DataSource omsCoreDatasource; private DataSource omsCoreDatasource;
@Resource
private PowerJobPhysicalNamingStrategy powerJobPhysicalNamingStrategy;
public static final String CORE_PACKAGES = "com.github.kfcfans.powerjob.server.persistence.core"; public static final String CORE_PACKAGES = "com.github.kfcfans.powerjob.server.persistence.core";
/** /**
@ -57,7 +49,7 @@ public class CoreJpaConfig {
* *
* @return 配置Map * @return 配置Map
*/ */
private Map<String, Object> genDatasourceProperties() { private static Map<String, Object> genDatasourceProperties() {
JpaProperties jpaProperties = new JpaProperties(); JpaProperties jpaProperties = new JpaProperties();
jpaProperties.setOpenInView(false); jpaProperties.setOpenInView(false);
@ -67,11 +59,8 @@ public class CoreJpaConfig {
hibernateProperties.setDdlAuto("update"); hibernateProperties.setDdlAuto("update");
// 配置JPA自定义表名称策略 // 配置JPA自定义表名称策略
hibernateProperties.getNaming().setPhysicalStrategy(PowerJobPhysicalNamingStrategy.class.getName());
HibernateSettings hibernateSettings = new HibernateSettings(); HibernateSettings hibernateSettings = new HibernateSettings();
List<HibernatePropertiesCustomizer> customizers = new ArrayList<>();
customizers.add(
new NamingStrategiesHibernatePropertiesCustomizer(powerJobPhysicalNamingStrategy, null));
hibernateSettings.hibernatePropertiesCustomizers(customizers);
return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), hibernateSettings); return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), hibernateSettings);
} }
@ -93,32 +82,4 @@ public class CoreJpaConfig {
public PlatformTransactionManager initCoreTransactionManager(EntityManagerFactoryBuilder builder) { public PlatformTransactionManager initCoreTransactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(Objects.requireNonNull(initCoreEntityManagerFactory(builder).getObject())); return new JpaTransactionManager(Objects.requireNonNull(initCoreEntityManagerFactory(builder).getObject()));
} }
/**
* 参考 HibernateJpaConfiguration.NamingStrategiesHibernatePropertiesCustomizer
*/
private static class NamingStrategiesHibernatePropertiesCustomizer implements HibernatePropertiesCustomizer {
private final PhysicalNamingStrategy physicalNamingStrategy;
private final ImplicitNamingStrategy implicitNamingStrategy;
NamingStrategiesHibernatePropertiesCustomizer(PhysicalNamingStrategy physicalNamingStrategy,
ImplicitNamingStrategy implicitNamingStrategy) {
this.physicalNamingStrategy = physicalNamingStrategy;
this.implicitNamingStrategy = implicitNamingStrategy;
}
@Override
public void customize(Map<String, Object> hibernateProperties) {
if (this.physicalNamingStrategy != null) {
hibernateProperties.put("hibernate.physical_naming_strategy", this.physicalNamingStrategy);
}
if (this.implicitNamingStrategy != null) {
hibernateProperties.put("hibernate.implicit_naming_strategy", this.implicitNamingStrategy);
}
}
}
} }

View File

@ -1,14 +1,12 @@
package com.github.kfcfans.powerjob.server.persistence.config; package com.github.kfcfans.powerjob.server.persistence.config;
import com.github.kfcfans.powerjob.server.common.utils.PropertyUtils;
import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.io.Serializable; import java.io.Serializable;
import java.util.Locale;
/** /**
* 自定义表前缀配置项 oms.table-prefix 不配置时不增加表前缀 * 自定义表前缀配置项 oms.table-prefix 不配置时不增加表前缀
@ -21,24 +19,10 @@ import java.util.Locale;
* </p> * </p>
* *
* @author songyinyin * @author songyinyin
* @date 2020/7/18 下午 11:01 * @since 2020/7/18
* @since 3.2.0
*/ */
@Component public class PowerJobPhysicalNamingStrategy extends SpringPhysicalNamingStrategy implements Serializable {
public class PowerJobPhysicalNamingStrategy implements PhysicalNamingStrategy, Serializable {
@Value("${oms.table-prefix:}")
private String tablePrefix;
@Override
public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return apply(name, jdbcEnvironment);
}
@Override
public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return apply(name, jdbcEnvironment);
}
/** /**
* 映射物理表名称把实体表 AppInfoDO DO 去掉再加上表前缀 * 映射物理表名称把实体表 AppInfoDO DO 去掉再加上表前缀
@ -49,65 +33,14 @@ public class PowerJobPhysicalNamingStrategy implements PhysicalNamingStrategy, S
*/ */
@Override @Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) { public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
Identifier identifier = apply(name, jdbcEnvironment);
String text = identifier.getText(); String tablePrefix = PropertyUtils.getProperties().getProperty("oms.table-prefix");
String text = name.getText();
String noDOText = StringUtils.endsWithIgnoreCase(text, "do") ? text.substring(0, text.length() - 2) : text; String noDOText = StringUtils.endsWithIgnoreCase(text, "do") ? text.substring(0, text.length() - 2) : text;
String newText = StringUtils.hasLength(tablePrefix) ? tablePrefix + noDOText : noDOText; String newText = StringUtils.hasLength(tablePrefix) ? tablePrefix + noDOText : noDOText;
return new Identifier(newText, identifier.isQuoted()); return super.toPhysicalTableName(new Identifier(newText, name.isQuoted()), jdbcEnvironment);
} }
@Override
public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return apply(name, jdbcEnvironment);
}
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return apply(name, jdbcEnvironment);
}
private Identifier apply(Identifier name, JdbcEnvironment jdbcEnvironment) {
if (name == null) {
return null;
}
StringBuilder builder = new StringBuilder(name.getText().replace('.', '_'));
for (int i = 1; i < builder.length() - 1; i++) {
if (isUnderscoreRequired(builder.charAt(i - 1), builder.charAt(i), builder.charAt(i + 1))) {
builder.insert(i++, '_');
}
}
return getIdentifier(builder.toString(), name.isQuoted(), jdbcEnvironment);
}
/**
* Get an identifier for the specified details. By default this method will return an
* identifier with the name adapted based on the result of
* {@link #isCaseInsensitive(JdbcEnvironment)}
*
* @param name the name of the identifier
* @param quoted if the identifier is quoted
* @param jdbcEnvironment the JDBC environment
* @return an identifier instance
*/
protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) {
if (isCaseInsensitive(jdbcEnvironment)) {
name = name.toLowerCase(Locale.ROOT);
}
return new Identifier(name, quoted);
}
/**
* Specify whether the database is case sensitive.
*
* @param jdbcEnvironment the JDBC environment which can be used to determine case
* @return true if the database is case insensitive sensitivity
*/
protected boolean isCaseInsensitive(JdbcEnvironment jdbcEnvironment) {
return true;
}
private boolean isUnderscoreRequired(char before, char current, char after) {
return Character.isLowerCase(before) && Character.isUpperCase(current) && Character.isLowerCase(after);
}
} }

View File

@ -3,7 +3,7 @@ logging.config=classpath:logback-dev.xml
####### 数据库配置 ####### ####### 数据库配置 #######
spring.datasource.core.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.core.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.core.jdbc-url=jdbc:mysql://remotehost:3306/powerjob-daily?useUnicode=true&characterEncoding=UTF-8 spring.datasource.core.jdbc-url=jdbc:mysql://localhost:3306/powerjob-daily?useUnicode=true&characterEncoding=UTF-8
spring.datasource.core.username=root spring.datasource.core.username=root
spring.datasource.core.password=No1Bug2Please3! spring.datasource.core.password=No1Bug2Please3!
spring.datasource.core.hikari.maximum-pool-size=20 spring.datasource.core.hikari.maximum-pool-size=20

View File

@ -11,10 +11,10 @@ spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.max-file-size=209715200 spring.servlet.multipart.max-file-size=209715200
spring.servlet.multipart.max-request-size=209715200 spring.servlet.multipart.max-request-size=209715200
###### OhMyScheduler 自身配置(该配置只允许存在于 application.properties 文件中) ###### ###### PowerJob 自身配置(该配置只允许存在于 application.properties 文件中) ######
# akka ActorSystem 服务端口 # akka ActorSystem 服务端口
oms.akka.port=10086 oms.akka.port=10086
# 报警服务 bean名称 # 报警服务 bean名称
oms.alarm.bean.names=omsDefaultMailAlarmService oms.alarm.bean.names=omsDefaultMailAlarmService
# 表前缀 # 表前缀(默认无表前缀,有需求直接填入表前缀即可,比如 pj_
#oms.table-prefix=pj_ oms.table-prefix=