Search code examples
javahibernatecriteriahibernate-criteria

How to set fetch mode to retrieve single result from a collection in Hibernate?


I'm using Hibernate with criteria.

I have a java model defined like this;

@Entity
@Table(name = "questionask", uniqueConstraints = @UniqueConstraint(columnNames = "code"))
public class QuestionAsk extends LobEntity implements Comparable<Object> {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "questionAsk")
    private List<Answer> answerList = new Arraylist<Answer>(0);

//getters and settes

..
}

If I want to retrieve answer list with the fetched data, I set;

criteria.setFetchMode(property,  FetchMode.JOIN); //This works .

But My requirement is, I want to fetch some records from the collection, when user requests. That is, When user provides following query,(In the answerList each answer has code attribute)

answerList.code=an_123

I would like to retrieve the answerList with that single answer. But it does not working to me. (means, it is not fetching the answerList which I defined as lazy Loading)

I try like, criteria.setFetchMode(answerList, FetchMode.JOIN); with other required joins and ins.

How can I do this with criteria? Does Hibernate support this?


Solution

  • I don't think the use case you want is supported by hibernate.

    Why not invert the join you do : doing the query to get the Answers you want, and then getting the QuestionAsk linked to it ?

    You could even aggregate the result of this query in a Map<QuestionAsk, Set<Answer>>. This way there would be no ambiguity : mapEntry.getKey().getAnswerList() would return all the answers of a question, as expected, and mapEntry.getValue() would return the answers filtered.