如何在JPA命名查询中获取集合元素

时间:2017-06-19 15:56:41

标签: hibernate jpa

以下是My Named查询,我的测试用例输出列表正在重复 由于属性。我需要一个obj中的所有属性属于同一个测试用例

  

“选择t.Id,来自TestCase的atr将t.attributes作为atr加入”

public class TestCase {

@javax.persistence.Id
private Integer Id;

@Column(name="ui_order")
@OrderBy("uiorder desc")
private Integer uiorder;

@OneToMany(mappedBy="testCase")
@OrderBy("name DESC")
private Set<Attributes> attributes=new HashSet<Attributes>();
}


public class Attributes {

@Id
private Integer Id;

private String name;

@ManyToOne
@JoinColumn(name="test_case_id")
private TestCase testCase;

}

查询的输出是

[["id":1,"attributes":{"name":"Battery","id":1}],["id":1,"attributes":{"name":"Fan","id":2}]

所需的输出

[{"id":1,"attributes":[{"name":"Battery","id":1},{"name":"Fan","id":2}]}]

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

SELECT DISTINCT t FROM TestCase t LEFT JOIN FETCH t.attributes

答案 1 :(得分:0)

好像你想按ID分组,所以你只需要添加GROUP BY

SELECT t.id, atr
FROM TestCase t JOIN t.attributes as atr
GROUP BY t.id