Spring Data JPA @Column 注解無效

最近再寫一個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)列名符合駝峰命名法時,注解就無效了。

解決方案:

  1. @Column中的值變?yōu)樾憽?/li>
  2. 繼承ImprovedNamingStrategy 自定義策略。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容