使用自动创建表时,Hibernate 不会自动创建数据库序列

标签 hibernate postgresql orm sequence hbm2ddl

我想使用 Hibernate 和 Postgresql 自动创建我的数据库表,但我收到有关序列的错误。是否也可以使用 Hibernate 自动创建序列,或者我是否手动生成序列?

我的实体示例:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(uniqueConstraints = { @UniqueConstraint( columnNames =  { "id" }) })
@SequenceGenerator(name="SEQ_EXAMPLE_ID", sequenceName="example_id_seq", allocationSize=1)
public class Example {

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_EXAMPLE_ID")
    private Long id;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String g
}

hibernate 配置:

hbm2ddl.auto=create-drop
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true 

异常(exception)情况:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not get next sequence value

org.postgresql.util.PSQLException: ERROR: relation "example_id_seq" does not exist

最佳答案

您的映射似乎是正确的,我建议激活以下类别的日志记录以查看到底发生了什么:

  • org.hibernate.tool.hbm2ddl: Log all SQL DDL statements as they are executed

将其设置为 DEBUG 并检查 DDL 语句(可能会用相关部分更新问题)。

PS: allocationSize=1 不是很明智,使用默认值会更好。但那是无关的。

引用资料

关于使用自动创建表时,Hibernate 不会自动创建数据库序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3591062/

相关文章:

java - x.person 上的@OneToOne 或@ManyToOne 引用未知实体 : y. Person - 继承问题

python - 如何从 SQlAlchemy ORM session 中查询预先存在的表?

python - Django 左外连接

java - MyBatis 返回 hashmap 真实类型

java - 是否有一个类似 ORM 的 java 库,带有运行时定义的表来构建 sql 查询?

hibernate - ASM 3.1与HIbernate和JAX-RS的兼容性问题

java - 堆栈溢出错误: null in both side relationship

r - 查询表并生成国家代码分组和绘图条形图的代码

javascript - 类型错误 : Cannot read property 'rows' of undefined

postgresql - 快速获取最后插入的 n 行