I have trouble with JPA/Hibernate, no matter what I set fetch = FetchType.Lazy or fetch = FetchType.Eager.
My custom method not working (when debug, I see answers collection is PersistentBag and whenever I call getter, the answer is actually created and some condition with WITH in my custom was not applied). That's what I dont want, I want it will be set at my custom method.
Question is :
1, Am I doing right, disable fetch type and set association at hql query ?
2, If I am doing right, why it's not working, association only when call getter ?
3, If I am wrong, Please tell me how to implement this.
Thanks for reading .
My Parent
class :
@Entity
@NamedQuery(name="Question.findAll", query="SELECT q FROM Question q")
public class Question implements Serializable {
//bi-directional many-to-one association to Answer
@OneToMany(mappedBy="question",fetch=FetchType.LAZY)
@JsonManagedReference
private List<Answer> answers;
...
}
And Child
class :
@Entity
@NamedQuery(name="Answer.findAll", query="SELECT a FROM Answer a")
public class Answer implements Serializable {
//bi-directional many-to-one association to Question
@ManyToOne
@JoinColumn(name="question_id")
@JsonBackReference
private Question question;
...
}
In My custom method , I'm using HQL as :
public List<Question> search() {
String sql = "SELECT distinct(question)"
+ " FROM Question as question "
+ " LEFT JOIN question.answers as answer with answer.isDeleted = true";
List<Question> result = query.getResultList();
return result;
}
PS. I found I have very similar issue with this post https://stackoverflow.com/a/1372725 but I dont know how to follow his instruction.