JPA用法中字段起名規范


前兩天在學習Springboot使用JPA 來操作數據庫時,碰到一個問題,最終發現了JPA寫法中表字段名稱要寫規范。

記錄下來提醒自己。

 

CityEntity是一個City的實體類。

 1 @Table(name = "city")
 2 public class CityEntity {
 3 
 4     @Id
 5     @GeneratedValue
 6     private Long id;
 7 
 8     @Column(name="name",columnDefinition = "char(35) ")
 9     private String name;
10 
11     @Column(name="countryCode",columnDefinition = "char(3) ")
12     private String countryCode;
13 
14     @Column(name="district",columnDefinition = "char(20) ")
15     private String district;
16 
17     @Column(name="population",columnDefinition = "int(11) ")
18     private Long population;
19 
20 }

通過CityRepository.findall() 來查詢時,一直報錯,報錯說沒有country_code字段,而實體類里面明明寫的映射字段是countryCode ,但是JPA產生的SQL語句如下:

SELECT
	cityentity0_.id AS id1_0_,
	cityentity0_.country_code AS country_2_0_,
	cityentity0_.district AS district3_0_,
	cityentity0_. NAME AS name4_0_,
	cityentity0_.population AS populati5_0_
FROM
	city cityentity0_

  

最終原因是CityEntity里面

@Column(name="countryCode",columnDefinition = "char(3) ") 這段注解有問題,而問題就出在name="countryCode",這樣JPA會在產生SQL語句的時候自動解析成 country_code

解決方法就是寫成這樣:  @Column(name="countrycode",columnDefinition = "char(3) "),出來正確的SQL


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM