【问题标题】:Springboot JPA (Hibernate) not getting table and column by nameSpring Boot JPA(Hibernate)没有按名称获取表和列
【发布时间】:2021-02-09 18:24:26
【问题描述】:

当我将我的模型定义为 -

@Entity
@Table
public class User{

    @Id
    @NotNull
    private String employeeId;

}

我收到此错误 -

Caused by: org.postgresql.util.PSQLException: ERROR: column user0_.employeeid does not exist

但是当我使用这个时-

@Entity
@Table(name = "`User`")
public class User{

    @Id
    @NotNull
    @Column(name = "`employeeId`")
    private String employeeId;

}

在我的 application.yml -

spring:
  jpa:
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
      ddl-auto: update
    database-platform: org.hibernate.dialect.PostgreSQLDialect
  datasource:
    url: ${db.host}
    username: ${db.user}
    password: ${db.password}

为什么我在第一个中遇到错误?具体名字我就不说了,spring boot jpa应该会自动通过命名找到表和列。

我的表和列与我对实体和列的命名相同,我不想更改名称,这就是我使用PhysicalNamingStrategyStandardImpl

的原因

第一个有什么问题?

【问题讨论】:

  • 你使用hibernate.globally_quoted_identifiers属性吗?
  • @SternK 不,我没用过
  • @SternK 正如你所看到的,它正在寻找 user0_.employeeid 但它应该是 user0_.employeeId 它是两个小写字母
  • @SternK 我用true 试过了,现在它工作了!!谢谢 !您可以将其发布为答案

标签: spring spring-boot hibernate jpa


【解决方案1】:

其实你应该避免使用upper case table or column names。但是如果你不想改变它,你可以告诉hibernate使用global quoting

<property name="hibernate.globally_quoted_identifiers" value="true" />

【讨论】:

    【解决方案2】:

    首先,您使用的是传统的命名策略,而不是 Spring boot 提供的默认命名策略。 Hibernate 使用物理策略和隐式策略映射字段名称。 Hibernate 使用物理命名策略将我们的逻辑名称映射到 SQL 表及其列。 Spring Boot,为这两种策略提供默认值spring.jpa.hibernate.naming.physical-strategy 默认为org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategyspring.jpa.hibernate.naming.implicit-strategy 默认为org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy

    spring-boot 的默认命名策略为:

    • 用下划线替换点
    • 骆驼箱换蛇箱
    • 小写表名

    因此,如果您的数据库在创建表和列时遵循这些约定,那么您可以从 application.properties 中删除休眠命名策略键,spring 将通过从名称本身解析来自动选择表。

    【讨论】:

    • 不,我的表和列与我对实体和列的命名相同,我不想更改名称,这就是我使用PhysicalNamingStrategyStandardImpl的原因
    • @PankajSharma 如果是这种情况,请在启用休眠日志的情况下共享整个堆栈跟踪以进行更多分析。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    相关资源
    最近更新 更多