1
爲什麼Hibernate嘗試使用現有ID插入新記錄?爲什麼Hibernate嘗試使用現有ID插入新記錄?
分類表之前保存(用刀片手工填寫)
ID | NAME | IMAGE
1 | 'NAME'| 'IMAGE'
保存代碼
//Category{id=0, name='NAME', image='IMAGE', parent=null}
getCurrentSession().save(category);
應與ID 2
類別Java代碼
@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;
}
插入
解決方案
//Category
@GeneratedValue(strategy = GenerationType.IDENTITY)
//CategoryRelations
@Entity
@IdClass(CategoryRelationsPrimaryKey.class)
public static class CategoryRelationsPrimaryKey implements Serializable {
private Long categoryId;
private Long parentId;
,而不是長。