How to use JPA 2.0 @ManyToMany without issues

后端 未结 2 1295
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 00:46

I am using JPA 2.0 and Spring in my development. My entity class contains two @ManyToMany relationships.

@Entity(\"         


        
2条回答
  •  我在风中等你
    2020-12-18 01:17

    The best way is to make the XxxtoMany associations lazy (the default). This way, the collections will only be loaded when needed, or when you tell Hibernate to fetch them eagerly using a query with a join fetch clause. Making them EAGER forces Hibernate to always load them, even when you don't need them.

    Of course, if you need them and they are configured as LAZY, they can only be loaded if the session is still open. Once the session is closed, the entity becomes detached, and the collections can't be lazy-loaded anymore. You thus need to initialize them explicitly (by calling a method of the collection, or by invoking Hibernate.initialize(collection)) before closing the session.

    If you really want to keep them eagerly loaded, then only one of them should be a bag (i.e. of type Collection or List). The others should be declared as Set.

    Side note: the mapping of the second association is wrong: you're using the same join column twice.

提交回复
热议问题