如何设置获取模式以从 Hibernate 中的集合中检索单个结果?

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

我正在使用带条件的 Hibernate。

我有一个这样定义的 java 模型;

@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

..
}

如果我想用获取的数据检索答案列表,我设置;

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

但我的要求是,当用户请求时,我想从集合中获取一些记录。也就是说,当用户提供以下查询时,(在 answerList 中每个答案都有 code 属性)

answerList.code=an_123

我想检索包含该单个答案的 answerList。但这对我不起作用。 (意思是,它没有获取我定义为延迟加载的 answerList)

我试过, criteria.setFetchMode(answerList, FetchMode.JOIN);与其他必需的 joinsins.

我如何使用标准来做到这一点? Hibernate 支持这个吗?

我认为 hibernate 不支持您想要的用例。

为什么不反转您所做的联接:执行查询以获取您想要的 Answer,然后获取与之链接的 QuestionAsk

您甚至可以将此查询的结果汇总到 Map<QuestionAsk, Set<Answer>> 中。这样就不会有歧义:mapEntry.getKey().getAnswerList() 会 return 一个问题的所有答案,正如预期的那样,mapEntry.getValue() 会 return 过滤答案。