Spring Boot切换至data-jdbc报错:CONTENT.CONTENT_TYPE列不存在
问题解决:Spring Data JDBC 提示列CONTENT.CONTENT_TYPE不存在
问题场景
将Spring Boot项目从spring-boot-starter-jdbc切换为spring-boot-starter-data-jdbc搭配ListCrudRepository使用时,H2数据库持续抛出org.h2.jdbc.JdbcSQLSyntaxErrorException,提示列CONTENT.CONTENT_TYPE不存在。切回starter-jdbc后功能恢复正常。
原因分析
Spring Data JDBC默认采用驼峰转下划线的命名策略:实体类中的驼峰字段名(如contentType)会被自动转换为下划线分隔的数据库列名(content_type)。但你的数据库表中列名是驼峰格式的contentType,框架生成的SQL会去查找CONTENT_TYPE(下划线格式),因此出现列不存在的错误。而starter-jdbc是手动编写SQL或使用JdbcTemplate直接指定了正确的列名,所以没有问题。
解决方案
方案1:修改数据库表列名(推荐,符合数据库命名规范)
将SQL中的列名改为下划线格式,同时注意desc是H2关键字,需要用反引号包裹:
CREATE TABLE IF NOT EXISTS Content ( id INTEGER AUTO_INCREMENT, title varchar(255) NOT NULL, `desc` text, status VARCHAR(20) NOT NULL, content_type VARCHAR(50) NOT NULL, date_created TIMESTAMP NOT NULL, date_updated TIMESTAMP, url VARCHAR(255), primary key (id) ); INSERT INTO Content(title, `desc`, status, content_type, date_created) VALUES ('My Blog Post', 'This is a Blog Post', 'IDEA', 'ARTICLE', CURRENT_TIMESTAMP)
方案2:给实体字段添加@Column注解指定列名
在Content实体的contentType字段上添加@Column注解,明确对应数据库列名:
import org.springframework.data.relational.core.mapping.Column; import org.springframework.data.annotation.Id; public record Content( @Id Integer id, String title, String desc, Status status, @Column("contentType") Type contentType, LocalDateTime dateCreated, LocalDateTime dateUpdated, String url ) { }
方案3:全局配置命名策略为保留驼峰
在配置文件中设置Spring Data JDBC的命名策略,保留实体类的驼峰字段名:
# application.properties spring.data.jdbc.naming-strategy=org.springframework.data.relational.core.mapping.NamingStrategies.LOWER_CAMEL_CASE
# application.yml spring: data: jdbc: naming-strategy: org.springframework.data.relational.core.mapping.NamingStrategies.LOWER_CAMEL_CASE
内容的提问来源于stack exchange,提问作者calvinkaru
相关产品推荐
相关产品推荐

