简体   繁体   中英

NULL value somehow being assigned to ID field in H2 database SQL statement

I'm working on an H2 database, trying to get it to accept input from a webpage, and it keeps giving me the following error:

Caused by[m: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "ID"; SQL statement:
insert into BOOK (ID, AUTHOR, GENRE, ILLUSTRATOR, SERIES, TITLE) values (default, ?, ?, ?, ?, ?) [23502-214]

and I have no idea where it's getting this NULL value from. I've got the model kitted out

@Entity
@Table(name = "BOOK")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

and the DAO is set up to give me a non-null value

@Repository
public class DAOImpl implements DAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void saveBook(Book book) {
        book.setId(0L);
        
        Session s = sessionFactory.getCurrentSession();
        s.save(book);
    }

It just seems like the NULL is coming out of nowhere. What am I missing?

You need to check definition of your table. Because you use GenerationType.IDENTITY , the ID column must be defined as an identity column :

CREATE TABLE BOOK (
    ID BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    .....
);

If you want to prevent attempts to insert custom values instead of generated ones, you can use GENERATED ALWAYS AS IDENTITY instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM