Pankaj Sharma
Pankaj Sharma

Reputation: 2267

Springboot JPA (Hibernate) not getting table and column by name

When I am defining my model as -

@Entity
@Table
public class User{

    @Id
    @NotNull
    private String employeeId;

}

I am getting this error -

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

but when I am using this -

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

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

}

In my 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}

Why I am getting error in first one ? I don't want to specifically tell the names, spring boot jpa should automatically find the table and column by naming.

My tables and columns are same as my naming of entity and column, I don't want to change in the name, that's why I am using PhysicalNamingStrategyStandardImpl

What's wrong with 1st one ?

Upvotes: 1

Views: 1445

Answers (2)

SternK
SternK

Reputation: 13041

Actually, you should avoid to use upper case table or column names. But if you do not want to change it you can tell hibernate to use global quoting:

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

Upvotes: 1

Ananthapadmanabhan
Ananthapadmanabhan

Reputation: 6206

First of all ,you are using the legacy naming strategy instead of the default provided by Spring boot. Hibernate maps field names using a physical strategy and an implicit strategy. Hibernate uses the Physical Naming Strategy to map our logical names to a SQL table and its columns. Spring Boot, provides defaults for both these strategies spring.jpa.hibernate.naming.physical-strategy defaults to org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy, and spring.jpa.hibernate.naming.implicit-strategy defaults to org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy

The default naming strategy for spring-boot will :

  • Replace dots with underscores
  • Change camel case to snake case
  • Lower-case table name

So if your database follows these conventions while you created the tables and columns then you could remove the hibernate naming stratergy keys from application.properties and spring will automatically pick up the tables by resolving it from the name itself.

Upvotes: 1

Related Questions