休眠多对多关系集或列表? [英] Hibernate Many to Many Relations Set Or List?

查看:134
本文介绍了休眠多对多关系集或列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Java bean中有多对多的关系。当我使用 List 来定义我的变量时:

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

@ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE},fetch = FetchType。 EAGER)
@JoinColumn(name =b_fk)
私人列表< R> R等
//或
私人设定< R> R等

我得到这个错误:

<$ p $创建名为'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0'的bean时发生错误
...
org.springframework.beans.factory.BeanCreationException: c $ c>

当我使用 Set 时,一切看起来都很顺利。



我想问在使用多对多关系时,哪一个用于逻辑概念 List Set (因为列表可能有重复和设置,但是关于性能和其他问题)?

解决方案

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

>

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

第三件事 - 你不能有多个



另见: / p>


  • 19.5。了解收藏表现

  • 为什么Hibernate会删除所有然后重新插入 - 它并不那么奇怪


  • ul>

    I have a many to many relationship at my Java beans. When I use List to define my variables as like:

    @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:

    这篇关于休眠多对多关系集或列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆