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
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?
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
There are few alternatives you can use:
@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.
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
)