问题描述
我正在使用 Spring-boot 1.4.1.RELEASE,通过 Spring Data 和 Hibernate 将一些数据保存到 MySQL 数据库中.
I'm using Spring-boot 1.4.1.RELEASE, with Spring Data and Hibernate to persist some data into a MySQL database.
我有这个类,Respondent
,用 @Entity
注释,其中一个字段注释如下:
I have this class, Respondent
, annotated with @Entity
and one of the fields annotated as below:
@Column(name = "firstName", nullable = false, length = 100)
private String firstName;
当我尝试通过在其 CrudRepository
上调用 save()
将响应者保存到数据库时,我收到此错误:
When I try to save a Respondent to the DB by calling save()
on its CrudRepository<Respondent, Long>
, I get this error:
ERRORcom.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'first_name' in 'field list'
这个错误在我为字段添加 @Column
注释之前就开始发生了,所以我认为将 firstName 映射到 first_name 是一些默认的 Hibernate 行为,但我已经添加了 @Column
注释,没有任何改变.还是错了?我已经用 mvn clean package
重建了应用程序.
This error had started occurring before I had the @Column
annotation for the field, so I thought it was some default Hibernate behaviour to map firstName to first_name, but I've added the @Column
annotation to it and nothing changed. Is it still wrong? I've already rebuilt the application with mvn clean package
.
这是我的受访者实体:
@Entity
public class Respondent {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name = "firstName", nullable = false, length = 100)
private String firstName;
private String tussenvoegsel;
@Column(name = "lastName", nullable = false, length = 100)
private String lastName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "Company_id", nullable = false)
private Company company;
推荐答案
默认情况下,Spring 使用 jpa.SpringNamingStrategy
来生成表名.
By default Spring uses jpa.SpringNamingStrategy
to generate the table names.
ImprovedNamingStrategy
会将 CamelCase
转换为 SNAKE_CASE
,而 EJB3NamingStrategy
只是使用未更改的表名.
The ImprovedNamingStrategy
will convert CamelCase
to SNAKE_CASE
where as the EJB3NamingStrategy
just uses the table name unchanged.
您可以尝试将 naming_strategy
更改为:
You can try to change the naming_strategy
to:
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
或 @Column name
属性应该是小写的 @Column(name = "firstname")
or the @Column name
attribute should be in lowercase @Column(name = "firstname")
对于 Hibernate 5
这应该可以工作(我不太确定你是否还需要上面的一个.但是两个都试试):
For Hibernate 5
this should work (I am not quite sure if you also need the above one. But try it with both):
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
这篇关于Spring Data 似乎不理解@Column 名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!