【发布时间】:2018-05-08 14:45:58
【问题描述】:
我在 Wildfly 12 中使用 Java EE。我有以下 SQL 表方案:
CREATE TABLE AUTHOR ("ID" INTEGER primary key, "FIRSTNAME" VARCHAR(50) not null, "SECONDNAME" VARCHAR(50) not null);
CREATE TABLE BOOK ("ID" INTEGER primary key, "TITLE" VARCHAR(50) not null, "AUTHOR" INTEGER, FOREIGN KEY ("AUTHOR") REFERENCES AUTHOR("ID"));
我要执行以下插入:
INSERT INTO AUTHOR("SECONDNAME","FIRSTNAME") values ('a', 'b');
INSERT INTO BOOK("TITLE","AUTHOR") values ('bookTitle', 1);
我的persistence.xml:
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="javax.persistence.schema-generation.create-source" value="script"/>
<property name="javax.persistence.schema-generation.drop-source" value="script"/>
<property name="javax.persistence.schema-generation.create-script-source" value="META-INF/create.sql"/>
<property name="javax.persistence.schema-generation.drop-script-source" value="META-INF/drop.sql"/>
<property name="javax.persistence.sql-load-script-source" value="META-INF/load.sql"/>
这在我明确插入 ID 时有效。但是,ID 必须是自动生成的。我的实体类:
@Entity
@XmlRootElement
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
// rest of fields, getters, and setters omitted
}
@Entity
@XmlRootElement
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
// Again, rest of the fields, getters and setters omitted
}
我尝试了所有生成策略(AUTO、IDENTITY、SEQUENCE)。正如我所说,如果我在 SQL 中显式设置 ID,则 SQL 可以工作,但是在使用 entityManager.persist 时遇到同样的问题......
@POST
@Path("/create")
public void createAuthor(Author author) {
entityManager.persist(author);
}
以上所有都给了我:
Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ID"; SQL statement: ...
有什么帮助吗?
【问题讨论】:
标签: java hibernate jakarta-ee