OpenJPA - lazy fetching does not work

后端 未结 1 2116
挽巷
挽巷 2020-12-11 13:51

I have a specific problem with an unit test using embedded OpenEJB container. I have a bi-directional relation between two classes. In one direction the relation works prope

相关标签:
1条回答
  • 2020-12-11 14:34

    Its the problem with life cycle of enties. All enties (track and its sections) must be re-attached to the persistence context. The method collecting events must be in the class using EntityManager. (The entity cannot use the manager to re-attach itself.) Example of updated entity managing class follows:

    public class EntityDataAccessor {
        @PersistenceUnit(unitName = "someUnit")
        private EntityManagerFactory emFactory;
    
        //gets one track
        public Track getTrack(int number) {
            EntityManager em = emFactory.createEntityManager();
            try {
                return (Track)em.find(TrackEntity.class, number);
            }
            finally {
                em.close();
            }
        }
    
        //the new method collecting events
        public Collection<HistoricalEvent> getEventsForTrack(TrackEntity te) {
            EntityManager em = emFactory.createEntityManager();
            te = em.merge(te); //re-attach to the context
    
            Set<SectionEntity> sections = te.getSections();
            TreeSet<HistoricalEvent> set = new TreeSet<HistoricalEvent>();
            for (SectionEntity se : sections) {
                se = em.merge(se); //re-attach to the context
                set.addAll(se.getEvents());
            }
            em.close();
            return set;
        }
    }
    

    See question What's the lazy strategy and how does it work? for more detail.

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