JPA Lazy Loading

前端 未结 3 1679
一生所求
一生所求 2020-12-14 11:44

I have a problem with lazy loading property in JPA entity. I read many similar questions, but they are related to spring or hibernate and their answears are either not appli

相关标签:
3条回答
  • 2020-12-14 12:18

    LazyInitializationException means that you access a lazy collection AFTER the associated session had been closed.

    As your code looks fine, your problem may be the same like in this question LazyInitializationException in JPA and Hibernate

    Can you verify that your transaction is opened in the beginning of the method?

    0 讨论(0)
  • 2020-12-14 12:28

    To initialize laze in JPA, you need to invoke a jar library and start it, if it is with maven or manual por example , if you need laze, use jar in maven
    jar de.empulse.eclipselink More info http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Performance/Weaving/Static_Weaving#Use_the_Maven_plugin

    0 讨论(0)
  • 2020-12-14 12:36

    There are few alternatives you can use:

    Use cascading persistence:

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = {CascadeType.PERSIST})
    List<OAuthLogin> oauthLogins;
    

    In your Servlet do:

    User user = new User(name);
    user.setEmail(email);
    OAuthLogin fbLogin = new OAuthLogin(user, OAuthProvider.FACEBOOK, "1501791394");      
    user.getOauthLogins().add(fbLogin) // this is enough assuming uni-directional association
    userDAO.persist(user);
    List<OAuthLogin> oauthLogins = user.getOauthLogins();
    

    This should do, plus you have a single transaction and less JDBC calls.

    This is helpful for that specific use case where it that specific Servlet method call.

    pre-fetch collection in EJB

    public User findById(int id, boolean prefetch) {
        User entity = em.find(User.class, id);
        if (prefetch) {
            // Will trigger 1 or size JDBC calls depending on your fetching strategy
            entity.getOauthLogins().size() 
        }
        return entity;
    }
    

    Alternatively, Override fetch mode using a criteria

    This is helpful for every case you want to fetch OAuthLogin collection with the User while preserving a FetchType.LAZY and avoid LazyInitializationException for that specific collection only.

    Use Open Entity Manager in View Filter

    Just Google it, you'll find plenty of examples

    This will basically prevents LazyInitializationException, per every association fetched lazily, per each Entity application cross-wide

    PS:

    1. If not using Spring why are you using @Transactional (by default even doesn't apply to HttpServlet)
    2. It had worked for WebLogic probably using some kind of tailored made solution
    0 讨论(0)
提交回复
热议问题