【发布时间】:2016-04-05 06:33:04
【问题描述】:
我将 Hibernate 与 PostgreSQL 一起使用。我有一个 import.sql 文件,Hibernate 在创建/验证架构后执行该文件。相应地导入了内容,但是当我尝试通过我的应用程序保留新条目时,Hibernate 尝试使用从 1 开始的自动生成的主键,我的导入文件已经使用了这些主键。有没有办法解决这个问题?
我有一个所有其他实体都继承自的单一实体类,它使用GenerationType.AUTO 或GenerationType.IDENTITY。他们两个都没有工作:
@MappedSuperclass
public class Entidade implements Serializable {
private static final long serialVersionUID = -991512134416936719L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public Entidade() {
}
public Entidade(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
这是我的 persistence.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="...">
<jta-data-source>...</jta-data-source>
<class>...</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.default_schema" value="jcat" />
<property name="hibernate.hbm2ddl.import_files_sql_extractor"
value="org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.import_files" value="import.sql" />
<property name="hibernate.c3p0.min_size" value="5" />
<property name="hibernate.c3p0.max_size" value="20" />
<property name="hibernate.c3p0.max_statements" value="50" />
<property name="hibernate.c3p0.timeout" value="3000" />
<property name="hibernate.c3p0.idle_test_period" value="1800" />
</properties>
</persistence-unit>
</persistence>
【问题讨论】:
-
为什么不查看为 INSERT 调用的 SQL?
-
您需要更改 SQL 脚本,以便在脚本内调整序列。但是如果没有看到那个脚本,就不可能提供更多细节(基本上你不应该在那里使用硬编码的 ID,而是从序列中获取 ID)
-
如果我有需要填写的外键怎么办?使用硬编码的 ID,我可以确切地知道要放置哪些 ID,但是通过使用序列,我无法确定序列正在使用哪些值,因此我可以将它们放入外键中。
-
你不需要。只需使用例如引用生成的 ID
lastval()或使用数据修改 CTE。向我们展示您的 SQL 脚本。 StackOverflow 上有很多例子。 -
JPA“IDENTITY”的定义是在数据存储区中设置的生成值。这适用于 RDBMS 中的 AUTO_INCREMENT/SERIAL 类型功能。由于您使用了 INT,因此您颠覆了 JPA 机制。又名用户错误
标签: java hibernate postgresql jpa