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?
CodePudding user response:
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.