Skip to main content
 首页 » 编程设计

Spring Boot 的 Hibernate 字段命名问题(命名策略)

2025年01月19日19shihaiming

请注意,此代码确实适用于普通 Spring,但不适用于 Spring Boot(v1.3.3),是否有我遗漏的东西,因为它是从一个有效的 Spring 应用程序导入的。下面的代码来自 spring boot 应用程序

@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; 

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

编辑: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 

请您参考如下方法:

自 SPRING-BOOT 1.4

从1.4开始,由于切换到Hibernate 5,命名策略更新为SpringPhysicalNamingStrategy其中should be very close到 1.3 默认值。

另见:

  • Spring's naming strategy


  • 以前的版本

    Spring Boot 提供了 ImprovedNamingStrategy 作为默认命名策略,这使得 Hibernate 搜索 team_id列(从 int teamId 字段推断)。由于您的表中不存在此列,因此这就是错误的原因。来自 Hibernate 文档:

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



    你有两个选择:
  • 明确提供列名 @Column(name="teamId") .曾经有一个 bug在早期引导版本中使用此功能,不再使用。
  • 更改命名策略 在 Spring Boot 属性中并告诉它使用 EJB3NamingStrategy ,它不会将camelCase 转换为snake_case,而是保持原样。