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:
- If not using Spring why are you using
@Transactional
(by default even doesn't apply to HttpServlet
)
- It had worked for WebLogic probably using some kind of tailored made solution
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…