【问题标题】:Spring-Data JPA: How to make a jpa criteria querySpring-Data JPA:如何进行 jpa 条件查询
【发布时间】:2013-01-15 10:31:48
【问题描述】:

鉴于这两个实体:

post         post_category
  - id         - post_id
  - title      - name
  - text

我想使用 jpa 标准查询进行此查询:

select * from post
where post.id in (
  select post_id from post_category
  where name = '<category1>' and name = '<category2>' ... and name = '<categoryN>')

【问题讨论】:

标签: criteria-api spring-data-jpa


【解决方案1】:

查看您的查询草图,我认为它不会返回任何结果。我把它改成了name in ('&lt;category1&gt;','&lt;category2&gt;', ...)。这可能与您的情况不符。

这假设您已在您的类上正确设置映射以使 JPA 工作。例如

    class PostCategory {
        private String name;
        private Post post;
        ...
        @ManyToOne
        public Post getPost() {
            return post;
        }
        ...

在这种情况下,您的 DAO 代码将类似于此(给定 List nameValues 对象)

    // Set up the subquery
    DetachedCriteria dc = DetachedCriteria.forClass(PostCategory.class)
        .setProjection(Projections.property("post.id"))
        .add(Restrictions.in("name", nameValues));

    Criteria crit = session.createCriteria(Post.class)
        .add(Subqueries.eqProperty("id", dc));

但是,如果您想要一个包含所有类别的 Post 对象列表,那么您需要为每个类别创建一个单独的 DetachedCriteria 实例,并将每个对象添加为 AND 的子查询。

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2017-04-25
    • 2015-08-04
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多