2016-05-14 70 views
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; 

,而不是長。

回答

2

這是因爲你已經刪除/添加從數據庫中的記錄直接而不是應用程序,即ORM,這就是爲什麼在hibernate_sequence值不再保留。

Hibernate在hibernate_sequence表中維護值,該表將在創建新記錄時插入。

更新next_valhibernate_sequence列值來解決問題。

您可以使用註釋@GeneratedValue(strategy = GenerationType.IDENTITY)到主鍵生成委託給數據庫。

相關問題