增加allocationSize会生成NonUniqueObjectException

时间:2011-10-21 09:32:06

标签: java hibernate jpa

我正在尝试将Mother个对象的集合插入到我的(Oracle)数据库中,这些对象具有Child个对象的列表。这些对象的所有id都是使用序列生成的:

@Entity
@Table(name = "MOTHER")
public class Mother implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SEQ_MOTHER")
    @SequenceGenerator(name="SEQ_MOTHER", allocationSize=100)  //Error?!?
    @Column(name = "ID")
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "mother", 
               orphanRemoval = true)
    private List<Child> children;    
}

由于Mother方法,我只需插入数千个persist个实例:

    for (Mother mother : mothersToInsert) {
        entityManager.persist(mother);
    }

在我的模型中,f我没有设置任何allocationSize(根据文档默认为50)或将其设置为小于50的值,然后一切运行正常。

然而,如果我尝试将其设置为100或更高,那么我会继续NonUniqueObjectException

javax.persistence.PersistenceException: org.hibernate.NonUniqueObjectException: 
    a different object with the same identifier value was already associated with 
    the session

解决方案”可以更改Cascade(我没有尝试更改它)但我希望在持久化母版实例时保留所有子实例(和检索它们......)

可能不需要将alocationSize设置为高值,但是如何在不获取该异常的情况下增加插入性能呢?如何确保即使不设置错误也不会隐藏在某个地方?

1 个答案:

答案 0 :(得分:0)

您必须将生成器的allocationSize设置为与序列中的“INCREMENT BY”相同的值。 Read this了解有关使用JPA排序的更多信息。