前两天在学习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