I have a Spring application combined with Hibernate to write some services which I can consume. I do not have a view, because these are service calls from a mobile phone which sends and gets JSON results.
So I have a Controller which handles the REST call:
@Controller
@RequestMapping(value = "/test")
public class TestController {
@Autowired
private TestService testService;
…
@RequestMapping(value = "/", method = RequestMethod.PUT)
public ResponseEntity<Map<String, Object>> testMethod(
@RequestHeader("userid") Integer userid, …) {
User user = testService.getUserById(userid);
List<Phone> phones = user.getPhones();
phones.add(…);
…
}
}
If I try to access the Phones, I get a org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.pojo.User.phones, no session or session was closed.
I have the two POJO classes User and Phone annotated in this way, so the User is the owner of this one-to-many relationship:
@OneToMany(cascade = { CascadeType.ALL })
@JoinColumn(name = "USER_ID")
private List<Phone> phones;
@ManyToOne
@JoinColumn(name = "USER_ID", insertable = false, updatable = false, nullable = false)
private User user;
My structure is Service -> ServiceImplementation and Dao -> DaoImplementation.
The ServiceImplementation method getUserById(userid) is annotated @Transactional.
How can I solve this problem? I know, that in this service REST call I always need to get the List of phones. I read sth. about OpenSessionInView, but it seems to be a pattern for using a view, which I do not have.
Putting a Hibernate.initialize(user.getPhones()); in front of List<Phone> phones = user.getPhones(); does not work.
I know this is a common problem, but I do not know how to solve in my case.