我在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: ...
任何帮助?
答案 0 :(得分:3)
您只是声明ID
列是INTEGER
和PRIMARY KEY
。您从未设置该列应自动递增,因此错误消息是正确的。将您的DDL更改为:
CREATE TABLE AUTHOR (
"ID" INTEGER primary key auto_increment,
"FIRSTNAME" VARCHAR(50) not null,
"SECONDNAME" VARCHAR(50) not null
);
CREATE TABLE BOOK (
"ID" INTEGER primary key auto_increment,
"TITLE" VARCHAR(50) not null,
"AUTHOR" INTEGER, FOREIGN KEY ("AUTHOR") REFERENCES AUTHOR("ID")
);