halpdoge
halpdoge

Reputation: 712

NULL not allowed for column "ID" H2 Hibernate

I am using Java EE with Wildfly 12. I have the following SQL table scheme:

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"));

I want to execute the following insert:

INSERT INTO AUTHOR("SECONDNAME","FIRSTNAME") values ('a', 'b');
INSERT INTO BOOK("TITLE","AUTHOR") values ('bookTitle', 1);

My 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"/>

This works when I explicitly insert ID. However, the ID has to be auto-generated. My entity classes:

@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
}

I've tried all generation strategies (AUTO, IDENTITY, SEQUENCE). As I said, if I explicitly set IDs in my SQL, the SQL works, but I encounter the same problem when using entityManager.persist...

@POST
@Path("/create")
public void createAuthor(Author author) {
    entityManager.persist(author);
}

All of the above gives me:

Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ID"; SQL statement: ...

Any help?

Upvotes: 2

Views: 6407

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You have only stated that the column ID is INTEGER and PRIMARY KEY. You have never set that the column should be auto increment, so the error message is right. Change your DDL to:

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")
);

Upvotes: 8

Related Questions