spring - H2 JdbcSQL异常 : "Table not found" with camelcase table & entity name

标签 spring hibernate jpa spring-data-jpa h2

使用 Spring Boot,以及 Spring Data JPA 和 H2 内存数据库(如果有所不同,则使用 PostgreSQL 模式)。

我有一个名为 ContentBlock 的表和实体类,但是当我执行 findAll() 时,H2 提示缺少 CONTENT_BLOCK 表或 findOne():

org.h2.jdbc.JdbcSQLException: Table "CONTENT_BLOCK" not found

我不确定大写/驼峰式是否有区别,但是 CONTENT_BLOCK 中的下划线从何而来?

在我的架构定义中:

CREATE TABLE ContentBlock (
  id       BIGSERIAL PRIMARY KEY,
  content  TEXT
  -- etc
);

在实体类中:

@Entity
@Table(name = "ContentBlock")
public class ContentBlock {
    // ...
}

(当然,我首先尝试不使用 @Table 注释,因为类名与表名完全匹配。)

对于我的其他表/实体,名称如 Asset,没有问题,我不需要在 Java 端显式指定表名:

@Entity   
public class Asset {
    // ...
}

在我的设置中,H2 数据源是这样明确定义的:

@Bean
public DataSource devDataSource() {  
        return new EmbeddedDatabaseBuilder()
          .generateUniqueName(true)
          .setType(EmbeddedDatabaseType.H2)
          .setScriptEncoding("UTF-8")
          .ignoreFailedDrops(true)
          .addScripts("database/init.sql", "database/schema.sql", "database/test_data.sql")
          .build();
    }

(init.sql的内容是SET MODE PostgreSQL;)

作为变通方法,我刚刚在 schema.sql 中将 ContentBlock 表重命名为 Block,使用 @Table(name = "Block") 在我仍然称之为 ContentBlock 的 Java 类中。

但这很奇怪,您确定可以通过某种方式将驼峰命名的表映射到实体吗?

最佳答案

默认 Spring Boot 使用 SpringNamingStrategy .它从 Hibernate 4 扩展 org.hibernate.cfg.ImprovedNamingStrategyImprovedNamingStrategy 在表名中生成下划线。

要将具有驼峰式名称的表映射到实体,您可以使用 org.hibernate.cfg.EJB3NamingStrategy 或实现您自己的。

使用属性设置名称策略的示例

spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy

关于spring - H2 JdbcSQL异常 : "Table not found" with camelcase table & entity name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33519630/

相关文章:

java - Jpa条件,将枚举类型转换为字符串

java - spring data jpa中的store是什么?

java - Post API 没有给出任何反应

json - spring boot --spring.application.json 参数未设置

eclipse - 运行动态 web 项目 tomcat "Only a type can be imported. org.hibernate.cfg.Configuration resolves to a package"时出现问题

java - Spring 启动: Handle Raised Exception from Database Trigger

java - 使用 Play 寻找多对多实体交集的优雅方式

java - HTTP 404 错误 :Resource Not Found - STS

java - Hibernate,从抽象父对象获取子对象

java - JPA 强制插入相关实体(而不是更新)