gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:40 24 4
gpt4 key购买 nike

请注意,此代码确实适用于普通 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 Boot 提供 ImprovedNamingStrategy作为默认命名策略,这使得 Hibernate 搜索 team_id 列(从 int teamId 字段推断)。由于您的表中不存在此列,这就是错误的原因。来自 Hibernate 文档:

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

您有两个选择:

  1. 明确提供列名称,如 @Column(name="teamId")。曾经有一个bug在早期的 Boot 版本中不再有此功能。

  2. 更改 Spring Boot 属性中的命名策略并告诉其使用 EJB3NamingStrategy ,它不会将camelCase转换为snake_case,而是保持原样。

关于Spring Boot 的 Hibernate 字段命名问题(命名策略),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60355407/

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