'How to generate entity id on DB side?
This is my Book entity:
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "BOOKS")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "AUTHOR_ID", referencedColumnName = "Id")
private Author author;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "GENRE_ID", referencedColumnName = "Id")
private Genre genre;
}
I try to insert new Book im my test method:
@Test
void insertBookTest() {
Author a3 = new Author(3L, "New Author");
Genre g3 = new Genre(3L, "New Genre");
Book actualBook = new Book()
.setId(3L)
.setName("Good Night")
.setAuthor(a3)
.setGenre(g3);
Book savedBook = bookService.insert(actualBook);
assertEquals(actualBook.getId(), savedBook.getId());
}
but i get exception:
org.hibernate.PersistentObjectException: detached entity passed to persist
I use H2 version 2.0.204, it was planned to generate entity id on DB side, for this i did schema.sql
DROP TABLE IF EXISTS AUTHOR;
CREATE TABLE AUTHOR(ID BIGINT PRIMARY KEY auto_increment, NAME VARCHAR(255));
DROP TABLE IF EXISTS GENRE;
CREATE TABLE GENRE(ID BIGINT PRIMARY KEY auto_increment, NAME VARCHAR(255));
DROP TABLE IF EXISTS BOOKS;
CREATE TABLE BOOKS(
ID BIGINT PRIMARY KEY auto_increment,
NAME VARCHAR(255),
AUTHOR_ID BIGINT REFERENCES AUTHOR(ID),
GENRE_ID BIGINT REFERENCES GENRE(ID),
foreign key (GENRE_ID) references GENRE(id) on delete cascade,
foreign key (AUTHOR_ID) references AUTHOR(id) on delete cascade);
this means that when insert a new entity I don't need to set Id, so when I move this setter
.setId(3L)
I get new exception:
NULL not allowed for column "ID"; SQL statement: insert into books (id, author_id, genre_id, name) values (null, ?, ?, ?) [23502-204]
How can I resolve this situation?
Solution 1:[1]
Hibernate ORM supports H2 2.*.* only since the version 5.6.5.Final. Older versions produce invalid SQL for identity columns, it is rejected by new versions of H2.
It will be better to upgrade H2 to the version 2.1.210 too, because Hibernate ORM also has some problems with indexes with H2 2.0.*.
You should normally use
ID BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEYinstead of MySQL-styleID BIGINT PRIMARY KEY auto_increment(unless you want to use the same SQL for both MySQL and H2).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Evgenij Ryazanov |
