最近再寫一個Restful API的小例子,遇到這樣一個問題,在Spring Boot 下使用CrudRepository,總是提示如下錯誤:
Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'userprofil0_.real_name' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:536)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:115)
at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:1983)
at com.mysql.cj.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1826)
at com.mysql.cj.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1923)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
... 76 more
而我的Bean這樣寫的:
@Entity
@Table(name = "eb_user_profile")
public class UserProfile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "UserID")
private Long UserID;
@Column(name = "UserName")
private String UserName;
@Column(name = "RealName")
private String RealName;
public UserProfile() { }
public UserProfile(String userName, String realName) {
UserName = userName;
RealName = realName;
}
getter...
setter...
}
于是spring.jpa.show-sql = true 打印SQL如下
Hibernate: select userprofil0_.userid as userid1_0_0_, userprofil0_.real_name as real_nam2_0_0_, userprofil0_.user_name as user_nam3_0_0_ from eb_user_profile userprofil0_ where userprofil0_.userid=?
啊咧咧,注解明明寫好了,為何映射的SQL還是帶下劃線的?
最后發(fā)動老夫的望氣之術(shù),終于在茫茫網(wǎng)海中找到這樣一段文字:
addUnderscores 用于處理 當(dāng)表名和列名在Java的種規(guī)則符合 UserNameTable(表)和 userNameColumn(列),就會被解析為user_name_table 和 user_name_column ,具體return的處理的是propertyToColumnName。 but呢,如果一旦配置了這個規(guī)則,(spring +jpa配置如下:
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy)
就會忽略了注釋中的@Column中的name,其實(shí)這個name地方就是為了映射數(shù)據(jù)庫字段,結(jié)果配置了這個就不care了。
http://blog.csdn.net/dracotianlong/article/details/27834143
因?yàn)榕渲昧薿rg.hibernate.cfg.ImprovedNamingStrategy 策略,因此當(dāng)列名符合駝峰命名法時,注解就無效了。
解決方案:
- 將
@Column中的值變?yōu)樾憽?/li> - 繼承
ImprovedNamingStrategy自定義策略。