如何在JPA Criteria中执行联接获取而不进行未经检查的强制转换? [英] How to perform a join fetch in JPA Criteria without unchecked casting?

查看:93
本文介绍了如何在JPA Criteria中执行联接获取而不进行未经检查的强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用静态元模型在JPA Criteria中进行JOIN FETCH,但是我在如何获得未检查的异常警告的情况下茫然无措.

I need to do a JOIN FETCH in JPA Criteria using a static metamodel, however I'm at a loss on how to do it without getting an unchecked exception warning.

假设我们有一个Thing实体,里面有一个延迟初始化的Other实体.我想用获取的Others检索事物,其中other.someField ="someValue".这大致就是我的做法:

Suppose we have a Thing entity with a lazily-initialized Other entity inside it. I want to retrieve Things with fetched Others, where other.someField="someValue". This is roughly how I would do it:

public List<Thing> getThings() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Thing> cq = cb.createQuery(Thing.class);
    Root root = cq.from(Thing.class);

    // This gives an unchecked cast warning:
    Join<Thing, Other> other = (Join<Thing, Other>) root.fetch(Thing_.other);

    cq.select(root).where(cb.equal(other.get(Other_.someField), "someValue"));

    return em.createQuery(cq).getResultList();
}

但是,由于Join和Fetch接口没有共同点,因此我收到未经检查的强制转换"警告.我想摆脱该警告(不使用@SuppressWarnings).

However, since the Join and Fetch interfaces have nothing in common, I get an "unchecked cast" warning. I would like to get rid of that warning (without using @SuppressWarnings).

我想我可以这样:

cb.equal(root.get(This_.THING).get(Other_.SOMEFIELD), "someValue"))

但是我怀疑它是否更好,因为我在这里使用String进行操作(因此没有类型安全性).

But I'm doubtful whether it's better, seeing as I'm operating on Strings here (so no type safety).

实现上述目标的更干净的方法是什么?

What is a cleaner way of achieving the above?

推荐答案

提取方法不应用于创建JPA联接.在JPA中,join用于创建where条件,而不是用于加载数据.这与本机SQL不同.对于JOIN使用:

Fetch method is not supposed for creating JPA joins. In JPA join is used to create where conditions, not for loading data. This is different from native SQL. For JOIN use:

Join<Thing, Other> other = root.join(Thing_.other);

可以在调用或不调用join()的情况下独立加载collection:

Independently collection can be loaded with or without calling join():

root.fetch(Thing_.other);

这篇关于如何在JPA Criteria中执行联接获取而不进行未经检查的强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆