Hibernate Many to Many Relations Set Or List?

后端 未结 3 1445
失恋的感觉
失恋的感觉 2020-12-22 20:52

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 G         


        
相关标签:
3条回答
  • 2020-12-22 21:05

    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:

    • 19.5. Understanding Collection performance

    • Why Hibernate does "delete all then re-insert" - its not so strange

    0 讨论(0)
  • 2020-12-22 21:16

    How about the uniqueness requirement from Set? Doesn't this force Hibernate to retrieve all objects each time one is added to the collection to make sure a newly added one is unique? A List wouldn't have this limitation.

    0 讨论(0)
  • 2020-12-22 21:20

    I know the question was made years ago but I wanted to comment on this topic, just in case someone is doubtful about the set vs list issue.

    Regarding lazy fetching, I think a bag (list without index) would be a better option due to the fact that you avoid retrieving all objects each time one is added to the collection to:

    • make sure a newly added one is unique, in case you are using a set
    • preserve order, in case you are using a list (with index)

    Please correct me if I'm mistaken.

    0 讨论(0)
提交回复
热议问题