且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

休眠多对多关系集或列表?

更新时间:2022-10-24 10:37:53

从关系数据库的角度来看,这是一个集合。数据库不保存顺序,并且使用 List 没有意义,它们的顺序没有指定(除非使用所谓的索引集合)。

>

使用 Set 也有很大的性能影响。当使用 List 时,Hibernate使用 PersistentBag 集合,其中有一些可怕的特性。 I.e .:如果你添加一个新的关系,它将首先删除所有现有的关系,然后将它们插回+你的新关系。 Set $ c>它只是插入新记录。

第三件事 - 你不能有多个



另见: / p>

@Entity
@Table(name="ScD")
public class Group extends Nameable {

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
    @JoinColumn(name="b_fk")
    private List<R> r;
    //or
    private Set<R> r;

I get that error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0'
...

When I use Set everything seem to work well.

I want to ask that when using many to many relationships which one to use for logical consept List or Set (because of list may have duplicates and set but what about performance and other issues)?

From relational databases perspective this is a set. Databases do not preserve order and using a List is meaningless, the order in them is unspecified (unless using so called indexed collections).

Using a Set also has great performance implications. When List is used, Hibernate uses PersistentBag collection underneath which has some terrible characteristics. I.e.: if you add a new relationship it will first delete all existing ones and then insert them back + your new one. With Set it just inserts the new record.

Third thing - you cannot have multiple Lists in one entity as you will get infamous cannot simultaneously fetch multiple bags exception.

See also: