创建一对多关系的QueryDSL谓词

时间:2018-12-12 16:06:30

标签: java jpa spring-data-jpa querydsl

我正在使用休眠JPA,Spring Data JPA和查询DSL。我正在尝试构造一个查询,该查询将过滤嵌套集合中的项目,但没有得到我想要的结果。

以下是JPA Bean:

@Entity
public class Item implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Item_ID")
    private long id;

    @OneToMany(mappedBy = "item")
    private Set<Operation> operations;
}

@Entity
public class Operation implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Operation_ID")
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "Item_ID")
    private Item item;

    @Column(name = "Name")
    @Size(max = 255)
    private String name;
}

为简洁起见,我省略了实体图注释。

我的存储库:

public interface ItemRepository extends JpaRepository<Item, Long>, QuerydslPredicateExecutor<Item>
{
}

最后是我的谓词:

final QItem item = QItem.item;
itemRepository.findAll(item.operations.any().name.eq(operationName), PageRequest.of(1, 10));

这将产生如下所示的SQL:

select ...
from [Item] item0_ 
left outer join [Operation] operations2_ on item0_.[Item_ID]=operations2_.[Item_ID] 
where exists (
    select 1 from [Operation] operations1_ 
    where item0_.[Item_ID]=operations1_.[Item_ID] 
    and operations1_.[Name]=?
)

我看到它正在返回所有项目,其中包括至少一个名称与operationName相匹配的操作。但是,每个Item内部的Set包含该项目具有的所有操作,我也希望这些操作也被operationName过滤,理想情况下是使用类似于以下内容的sql进行过滤:

select ...
from [Item] item0_ 
left outer join [Operation] operations2_ on item0_.[Item_ID]=operations2_.[Item_ID] 
where operations1_.[Name]=?

我已经尝试过:

final QOperation operation = QOperation.operation;
itemRepository.findAll(operation .name.eq(operationName), PageRequest.of(1, 10));

但是这会引发异常     org.hibernate.hql.internal.ast.QuerySyntaxException:无效路径:“ operation.name” [选择项 来自com.stackoverflow.example.Item项目

我猜这是因为item是查询路径的根,并且路径表达式必须以item开头并向下进行操作,但是我看不到该怎么做。

预先感谢

0 个答案:

没有答案
相关问题