Spring Boot+Hibernate查询报错:Unknown column 'country_code' 咨询
问题分析与解决:Hibernate找不到country_code列的问题
问题原因
你的City实体类里给countryCode字段加了@Column(name="countryCode"),但数据库的city表中对应的列实际是country_code(下划线命名)。Hibernate默认会把Java驼峰命名的字段自动转换为下划线分隔的数据库列名(比如countryCode→country_code),但你手动指定了name="countryCode",导致Hibernate生成SQL时去查找city0_.countryCode这个不存在的列,因此抛出SQL语法错误。删掉该字段后,Hibernate不会在查询中包含这个列,所以程序能正常运行,但这只是绕开了问题,不是根本解决。
解决方法
- 修正@Column的name属性:直接指定数据库实际的列名
country_code,代码如下:@Column(name = "country_code") private String countryCode; - 配置自动命名策略:如果不想每个字段都手动指定列名,可以在
application.properties(或application.yml)中配置Hibernate的命名策略,让它自动将Java驼峰字段映射为数据库下划线列名。比如添加:
配置后,spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImplcountryCode字段会自动对应数据库的country_code列,无需再手动写@Column的name属性。 - 验证数据库表结构:确认你的world数据库中city表确实存在
country_code列,避免是列名拼写错误或列本身不存在的问题。
内容的提问来源于stack exchange,提问作者akoluaciklinux
相关产品推荐
相关产品推荐

