gpt4 book ai didi

java - Spring Boot Hibernate 5 忽略@Table 和@Column

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:17:04 26 4
gpt4 key购买 nike

这让我发疯。

我正在实现 Spring Social,它要求您有一个名为 UserConnection 的数据库表(而不是使用使用下划线分隔两个词的标准命名约定)。

所以在我天真的世界观中,我认为通过指定 @Table(name="UserConnection") 可以很容易地解决这个问题......但是不,那太容易了。

注解被忽略,表被创建为 user_connection,然后导致 Spring Social 出现嘶嘶声。

请告诉我有一些简单的方法可以告诉我的 Spring Boot 应用只命名一个表(及其对应的列)以使用驼峰命名约定而不是标准命名约定。

最佳答案

TL;博士

将以下内容添加到您的 application.yml 文件中:

spring:
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

或者您的application.properties:

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

详细解答

作为 Spring Boot 1.4 release notes状态:

SpringNamingStrategy is no longer used as Hibernate 5.1 has removed support for the old NamingStrategy interface. A new SpringPhysicalNamingStrategy is now auto-configured which is used in combination with Hibernate’s default ImplicitNamingStrategy. This should be very close to (if not identical) to Spring Boot 1.3 defaults, however, you should check your Database schema is correct when upgrading.

这个新的 PhysicalNamingStrategy 遵循 Spring 推荐的命名约定。无论如何,如果您想完全控制物理命名,最好使用 org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl。您可以通过将以下内容添加到您的 application.yml 来切换到该命名策略:

spring:
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

The annotation is ignored and the table is created as user_connection which then causes Spring Social to have a hissy fit.

apply SpringPhysicalNamingStrategy 的方法是理解这种行为的关键:

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);
}

private boolean isUnderscoreRequired(char before, char current, char after) {
return Character.isLowerCase(before) && Character.isUpperCase(current)
&& Character.isLowerCase(after);
}

它基本上用下划线替换了所有 . 和大小写更改(查看 isUnderscoreRequired 方法)。

关于java - Spring Boot Hibernate 5 忽略@Table 和@Column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41912028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com