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
There are few alternatives you can use:
@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.
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.
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:
@Transactional
(by default even doesn't apply to HttpServlet
)