前兩天在學習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