JPA Lazy Loading

前端 未结 3 1680
一生所求
一生所求 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:36

    There are few alternatives you can use:

    Use cascading persistence:

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = {CascadeType.PERSIST})
    List 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 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

提交回复
热议问题