Hibernate field naming issue with Spring Boot (naming strategy)

ghz 1years ago ⋅ 9238 views

Question

Note that this code does work with plain Spring but not with Spring Boot(v1.3.3), is there something i'm missing because this is imported from a spring app that works. The code below is from the spring boot app

@Entity
@Table(name="project")
public class Project implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private int id;

    @Column(name="teamId")
    private int teamId;

    //private String Rentabiliteit;

    @Column
    //@Index(name="IProject_status",columnNames="Status")
    private String status;

    @Column
    //@Index(name="IProject_naam",columnNames="Naam")
    private String naam;
    //public Prototype m_Prototype;
    //public Team m_Team;

}

SQL

CREATE TABLE IF NOT EXISTS `project` (
`id` int(11) NOT NULL,
`teamId` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`naam` varchar(255) DEFAULT NULL
 ) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;

ERROR

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:           
 Unknown column 'project0_.team_id' in 'field list'

Edited: Application.yml

spring:

mvc:
  view:
    prefix: /WEB-INF/jsp/
    suffix: .jsp

datasource:
    url: jdbc:mysql://localhost:3306/oxyplast
    username: oxyplastuser
    password: oxyplastuserpw

jpa:
  properties:
    hibernate:
      current_session_context_class: org.springframework.orm.hibernate4.SpringSessionContext 
      namingStrategy: org.hibernate.cfg.DefaultNamingStrategy

Answer

SINCE SPRING-BOOT 1.4

Starting from 1.4, because of the switch to Hibernate 5, the naming strategy has been updated to SpringPhysicalNamingStrategy which [should be very close](https://github.com/spring-projects/spring-boot/wiki/Spring- Boot-1.4-Release-Notes#naming-strategy) to 1.3 defaults.

See also:


PREVIOUS VERSION

Spring Boot provides the ImprovedNamingStrategy as default naming strategy, which makes Hibernate search for a team_id column (inferred from the int teamId field). As this column doesn't exist in your table, that's the cause of the error. From the Hibernate docs:

An improved naming strategy that prefers embedded underscores to mixed case names

You've got two options:

  1. Provide the column name explicitly as @Column(name="teamId"). There used to be a bug with this in early Boot versions, not anymore.

  2. Change the naming strategy in the Spring Boot properties and tell it to use the EJB3NamingStrategy, which doesn't convert camelCase to snake_case, but keeps it as it is.