I've been working with RESTful service built by Spring MVC + Hibernate + MySQL.
In the database, I have two tables - topic and comment. ID column of topic table is the foreign key of the comment table. I generate the models and DAOs using Hibernate Tools:
Topic model:
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "topic")
public Set<Comment> getComments() {
return this.comments;
}
...
Comment model:
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "topic_id", nullable = false)
public Topic getTopic() {
return this.topic;
}
...
Here comes the question. I can get the detached topic object DT using findById()
. However, every time I want to send DT as the response body to the frontend, 'no session' exception is thrown because LAZY
object - comments, can only be accessed within the session.
1) if I don't change to EAGER
, my solution is to create new Topic
object NT and retrieve values (except comments) from the DT. Then return NT as the response body. Is this the best practice?
2) if I change the @OneToMany
part to EAGER
, the problem is still unsolved. Because when I send DT, set of comments are included, and every comment has relationship to topic as declared by @ManyToOne
. So still 'no session' exception is thrown.
3) if I change both @OneToMany
and @ManyToOne
to EAGER
, computer will stuck as it will go from topic to comment and back to topic, iteratively, never stop.
So, how you guys suggest to return topic as response body.