gpt4 book ai didi

hibernate - 如何使用JPA Criteria Builder编写查询(包括子查询和存在查询)

转载 作者:行者123 更新时间:2023-12-04 23:53:38 29 4
gpt4 key购买 nike

努力使用 JPA 编写以下查询。

甲骨文查询:

Select * from table1 s
where exists (Select 1 from table2 p
INNER JOIN table3 a ON a.table2_id = p.id
WHERE a.id = s.table3_id
AND p.name = 'Test');

另外,您是否想指出在 JPA 中编写复杂查询的任何好的教程。

最佳答案

我将使用 JpaRepository、JpaSpecificationExecutor、CriteriaQuery、CriteriaBuilder 回答简单汽车广告域(广告、品牌、模型)的示例:

  • 品牌 [一对多] 模型
  • 模型 [一对多] 广告

  • 实体:
    @Entity
    public class Brand {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @OneToMany(mappedBy = "brand", fetch = FetchType.EAGER)
    private List<Model> models;
    }

    @Entity
    public class Model {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name = "brand_id")
    private Brand brand;
    }

    @Entity
    public class Advert {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @ManyToOne
    @JoinColumn(name = "model_id")
    private Model model;
    private int year;
    private int price;
    }

    存储库:
    public interface AdvertRepository
    extends JpaRepository<Advert, Long>, JpaSpecificationExecutor<Advert> {
    }

    规范:
    public class AdvertSpecification implements Specification<Advert> {
    private Long brandId;

    public AdvertSpecification(Long brandId) {
    this.brandId = brandId;
    }

    @Override
    public Predicate toPredicate(Root<Advert> root,
    CriteriaQuery<?> query,
    CriteriaBuilder builder) {

    Subquery<Model> subQuery = query.subquery(Model.class);
    Root<Model> subRoot = subQuery.from(Model.class);

    Predicate modelPredicate = builder.equal(root.get("model"), subRoot.get("id"));

    Brand brand = new Brand();
    brand.setId(brandId);
    Predicate brandPredicate = builder.equal(subRoot.get("brand"), brand);

    subQuery.select(subRoot).where(modelPredicate, brandPredicate);
    return builder.exists(subQuery);
    }
    }

    效果是这个 Hibernate SQL:
    select advert0_.id as id1_0_,
    advert0_.model_id as model_id5_0_,
    advert0_.price as price3_0_,
    advert0_.year as year4_0_
    from advert advert0_
    where exists (select model1_.id from model model1_
    where advert0_.model_id=model1_.id
    and model1_.brand_id=?)

    关于hibernate - 如何使用JPA Criteria Builder编写查询(包括子查询和存在查询),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19222868/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com