最近再寫一個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還是帶下划線的?
最后發動老夫的望氣之術,終於在茫茫網海中找到這樣一段文字:
addUnderscores 用於處理 當表名和列名在Java的種規則符合 UserNameTable(表)和 userNameColumn(列),就會被解析為user_name_table 和 user_name_column ,具體return的處理的是propertyToColumnName。 but呢,如果一旦配置了這個規則,(spring +jpa配置如下:
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy)
就會忽略了注釋中的@Column中的name,其實這個name地方就是為了映射數據庫字段,結果配置了這個就不care了。
http://blog.csdn.net/dracotianlong/article/details/27834143
因為配置了org.hibernate.cfg.ImprovedNamingStrategy 策略,因此當列名符合駝峰命名法時,注解就無效了。
解決方案:
- 將
@Column
中的值變為小寫。 - 繼承
ImprovedNamingStrategy
自定義策略。
作者:naiive
鏈接:https://www.jianshu.com/p/ba87a9ee6001
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。