简体   繁体   English

为什么Hibernate尝试插入具有ID的新记录?

[英]Why Hibernate tries to insert new record with existed id?

Why Hibernate tries to insert new record with existing id? 为什么Hibernate尝试插入具有现有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. 应插入ID 2。

Category Java code 类别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;
}

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. 这是因为您直接从数据库而不是从应用程序(即ORM)中删除/添加了一条记录,这就是为什么hibernate_sequence中的值不再得到维护的原因。

Hibernate maintains values in a hibernate_sequence table which would be inserted on creating a new record. Hibernate会在hibernate_sequence表中维护值,该表将在创建新记录时插入。

update next_val column value in hibernate_sequence to resolve the problem. 更新hibernate_sequence next_val列值以解决该问题。

You can use Annotation @GeneratedValue(strategy = GenerationType.IDENTITY) to delegate primary key generation to database. 您可以使用Annotation @GeneratedValue(strategy = GenerationType.IDENTITY)将主键生成委派给数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM