Spring升级后JPA单元测试抛出JdbcSQLSyntaxErrorException求助
问题分析与解决方案
核心问题
报错的根源是Hibernate生成了H2数据库不兼容的Oracle风格DDL语句,同时你的JPA配置存在语法错误,导致Hibernate未能正确使用H2方言,最终触发VARCHAR2(255 CHAR)的语法报错(H2默认模式不支持该写法)。
步骤1:修复JPA配置的语法错误
你的配置文件中有两处明显的YAML语法错误,直接导致Hibernate方言加载异常:
database-platform=org:格式错误,应改为标准YAML键值对hbm2ddl.import_files_sql_extractor=org:格式错误,同样需要修正
修正后的完整配置:
spring: profiles: "test" jpa: properties: hibernate: globally_quoted_identifiers_skip_column_definitions: true hbm2ddl: import_files_sql_extractor: org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor connection: charSet: UTF-8 globally_quoted_identifiers: true database-platform: org.hibernate.dialect.H2Dialect show-sql: true hibernate: ddl-auto: create-drop defer-datasource-initialization: true h2: console: path: /console enabled: true datasource: url: jdbc:h2:mem:testdb;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE driver-class-name: org.h2.Driver username: sa password: data: classpath:data.sql
步骤2:让H2兼容Oracle风格语法
在数据源URL中添加MODE=Oracle参数,让H2切换到Oracle兼容模式,这样就能识别VARCHAR2(255 CHAR)这类Oracle风格的DDL语句。
备选方案:修改实体类注解(无需依赖H2兼容模式)
如果不想依赖H2的Oracle兼容模式,可以直接修改实体类的@Column注解,让Hibernate生成H2原生支持的DDL:
@Id @Column(name = "asset_entlmt_type_id", nullable = false, unique = true) private Integer assetEntitlementTypeId; // 改为H2兼容的列定义 @Column(name = "asset_entlmt_type_desc", length = 255) private String assetEntitlementTypeDesc; @Column(name = "crtd_by") private String createdBy;
或者显式指定列类型:
@Column(name = "asset_entlmt_type_desc", columnDefinition = "VARCHAR(255)") private String assetEntitlementTypeDesc;
额外注意事项
- 确保H2版本与Spring Boot 2.7.9兼容:Spring Boot 2.7.x默认适配H2 2.1.214版本,避免随意更换非兼容版本
- 检查
data.sql中的语句,确保没有使用H2不支持的Oracle语法
内容的提问来源于stack exchange,提问作者user2912181
相关产品推荐
相关产品推荐

