Why Hibernate tries to insert new record with existing id?
Category table before save (was filled manually with insert)
ID | NAME | IMAGE
1 | 'NAME'| 'IMAGE'
Save code
//Category{id=0, name='NAME', image='IMAGE', parent=null}
getCurrentSession().save(category);
Should be inserted with id 2.
Category Java code
@Entity
@Table(name = "CATEGORY",
indexes = {
@Index(name = "CATEGORY_NAME_INDEX",
columnList = "CATEGORY_NAME")})
public class Category implements NamedModel {
@Id
@Column(name = "CATEGORY_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
@Size(min = 1, max = 256)
@Column(name = "CATEGORY_NAME", length = 256)
private String name;
@OneToOne(fetch = FetchType.EAGER)
@JoinTable(name = "CATEGORY_RELATIONS",
joinColumns = {
@JoinColumn(name = "CATEGORY_RELATIONS_CATEGORY_ID",
referencedColumnName = "CATEGORY_ID")},
inverseJoinColumns = {
@JoinColumn(name = "CATEGORY_RELATIONS_PARENT_ID",
referencedColumnName = "CATEGORY_ID")})
private Category parent;
@OneToMany(cascade = {CascadeType.REMOVE, CascadeType.PERSIST},
fetch = FetchType.LAZY, mappedBy = "parent")
private List<Category> children;
}
SOLUTION
//Category
@GeneratedValue(strategy = GenerationType.IDENTITY)
//CategoryRelations
@Entity
@IdClass(CategoryRelationsPrimaryKey.class)
public static class CategoryRelationsPrimaryKey implements Serializable {
private Long categoryId;
private Long parentId;
instead of long.
This is because you had deleted/added a record from database directly instead from the application ie 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.
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.