Arthur Arthur - 1 year ago 38
Java Question

Why Hibernate tries to insert new record with existed id?

Why Hibernate tries to insert new record with existing id?

Category table before save (was filled manually with insert)

1 | 'NAME'| 'IMAGE'

Save code

//Category{id=0, name='NAME', image='IMAGE', parent=null}

Should be inserted with id 2.

Category Java code

@Table(name = "CATEGORY",
indexes = {
@Index(name = "CATEGORY_NAME_INDEX",
columnList = "CATEGORY_NAME")})
public class Category implements NamedModel {
@Column(name = "CATEGORY_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Size(min = 1, max = 256)
@Column(name = "CATEGORY_NAME", length = 256)
private String name;
@OneToOne(fetch = FetchType.EAGER)
@JoinTable(name = "CATEGORY_RELATIONS",
joinColumns = {
referencedColumnName = "CATEGORY_ID")},
inverseJoinColumns = {
referencedColumnName = "CATEGORY_ID")})
private Category parent;
@OneToMany(cascade = {CascadeType.REMOVE, CascadeType.PERSIST},
fetch = FetchType.LAZY, mappedBy = "parent")
private List<Category> children;


@GeneratedValue(strategy = GenerationType.IDENTITY)

public static class CategoryRelationsPrimaryKey implements Serializable {
private Long categoryId;
private Long parentId;

instead of long.


This is because you had deleted a record from database directly instead from the application i.e. ORM, that's why values in hibernate_sequence is no longer maintained.

Hibernate maintains values in a hibernate_sequence table which would be inserted on creating a new record.

update next_val column value in hibernate_sequence to resolve the problem.

You can use Annotation @GeneratedValue(strategy = GenerationType.IDENTITY) to delegate primary key generation to database.