JPA-hibernate@Table(name=“动态表名”)记录⼀下hibernate动态设置表名的⼀些坑
⾸先maven引⼊等不贴了,到这⼀步,⼀般来说,maven肯定引⼊了
⾸先需要⾃定义⼀个类,主要⽤来解析表达式spring framework documentation
import org.del.naming.Identifier;
import org.del.naming.PhysicalNamingStrategyStandardImpl;
import v.spi.JdbcEnvironment;
import org.springframework.beans.BeansException;
import t.ApplicationContext;
import t.ApplicationContextAware;
import t.expression.BeanFactoryAccessor;
import t.expression.BeanFactoryResolver;
import pression.Expression;
import pression.ParserContext;
import pression.spel.standard.SpelExpressionParser;
import pression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
/**
* ⾃定义命名策略(实现⽀持解析#{javaConfig.property}获取表名功能 )
*
* @author  Java⼤笨笨
* @since 2019-03-26
*/
@Component
public class MySpringPhysicalNamingStrategy extends PhysicalNamingStrategyStandardImpl
implements ApplicationContextAware {
private final StandardEvaluationContext context = new StandardEvaluationContext();
private final SpelExpressionParser parser = new SpelExpressionParser();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
String nameStr = Text();
ains(ParserContext.ExpressionPrefix())){
//参考SimpleElasticsearchPersistentEntity 实现思想,将tableName参数的值⽀持表达式获取
Expression expression = this.parser.parseExpression(nameStr, ParserContext.TEMPLATE_EXPRESSION);
Identifier((t, String.class));
}else {
//默认⽅式不变
PhysicalTableName(name, jdbcEnvironment);
}
}
}
  注意,这个类要继承⼀个PhysicalNamingStrategyStandardImpl,这个取决于你⽬前项⽬中的naming.physical-strategy,我之前⽤的是PhysicalNamingStrategyStandardImpl,所以这⾥继承并重新toPhysicalTableName⽅法。
yml配置
spring:
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: none
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
properties:
hibernate.format_sql: false
hibernate.naming.physical-strategy: xxxxx你的包名.MySpringPhysicalNamingStrategy
hibernate.cache.use_second_level_cache: false
hibernate.search.default.directory_provider: filesystem
hibernate.search.default.indexBase: c:\\xxxx
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author java⼤笨笨
* @create 2021-02-23 16:07
*/
@Component("optionsConfig")
public class OptionsConfig {
@Value("${site.options.table_name}")
private String optionsTableName;
public String getOptionsTableName() {
return optionsTableName;
}
public void setOptionsTableName(String optionsTableName) {
this.optionsTableName = optionsTableName;
}
}
  注意@Component("optionsConfig"),给个名字,否则会在表达式解析时候不到这个类 */
@Entity
@Table(name = "#{optionsConfig.optionsTableName}")
public class Options {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
…………
  最后这样,在name中写⼊表达式即可

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。