2017-07-07 56 views
1

由于代码库已经在使用Spring Data JPA,我想创建一个排序 对象,该对象将基于一个对象的存在(或缺少)特定元素 出现在集合本身中,该集合本身是 主表中的元素之一。 Sort对象的属性需要是动态的,因为用户可能希望以一种方式对下一次记录进行排序。Spring Data JPA,基于嵌套集合中可能条目的动态排序

明确,如果有多个PrimaryEntity对象具有设置为特定 值“类型”一SecondaryEntity,然后,我会希望他们在相应的 SecondaryEntity在相应的“注释”字段基础进行排序。此外,虽然我想要检索所有SecondaryEntity对象,但我希望 排序仅基于SecondaryEntity记录,其中'type'等于'重要'。

的类看起来如下(我也重新定义了“等于”为SecondaryEntity &“的hashCode”):

public class PrimaryEntity 
{ 

@OneToMany(mappedBy = "primary", cascade = CascadeType.ALL) 
@MapKey(name = "type") 
private Map<String, SecondaryEntity> myMap = new HashMap<>(); 

@Column(name = "name") 
private String name; 

} 

public class SecondaryEntity 
{ 

@Column(name = "type", length = 200) 
private String type; 

@Column(name = "notes", length = 2000) 
private String notes; 

@ManyToOne 
@JoinColumn(name = "primary_id", referencedColumnName = "id") 
private PrimaryEntity primary; 

} 

然后我会想创造一种类似于他语法如下:

排序排序=新的排序(“MYMAP [重要] .notes”)

最后,虽然我努力的PrimaryEntity记录按照上述排序,这不要紧, 我怎么样,对于一个给定PrimaryEntity,其S显示二级实体记录。

例如,

<html> 
<head> 
<style> 
table, th, td { 
    border: 1px solid black; 
    border-collapse: collapse; 
} 
</style> 
</head> 
<body> 
<table> 
    <tr> 
    <th>Name</th> 
    <th>Type</th> 
    <th>Notes</th> 
    </tr> 
    <tr> 
    <td>Second primary</td> 
    <td>Important</td> 
    <td>1</td> 
    </tr> 
    <tr> 
    <td>Second primary</td> 
    <td>Other</td> 
    <td>2</td> 
    </tr> 
    <tr> 
    <td>Second primary</td> 
    <td>Miscellaneous</td> 
    <td></td> 
    </tr> 
    <tr> 
    <td>Third primary</td> 
    <td>Important</td> 
    <td>2</td> 
    </tr> 
    <tr> 
    <td>First primary</td> 
    <td>Important</td> 
    <td>3</td> 
    </tr> 
</table> 
</body> 
</html> 

谢谢。

+0

你看过定制存储库吗? –

+0

你好,如果答案帮助你不要忘记接受/ upvote它。 – Cepr0

回答

0

您可以选择覆盖在SecondaryRepofindAll(Sort sort)@EntityGraph注释:

public interface SecondaryRepo extends JpaRepository<Secondary, Long> { 

    @EntityGraph(attributePaths = {"primary"}) 
    @Override 
    List<Secondary> findAll(Sort sort); 
} 

急切地获取相关的初选。

然后,只需定义Sorttypenote并获取二级工具(这将也含有初选)是这样的:

Sort sort = new Sort(new Sort.Order("type"), new Sort.Order("note")); 
List<Secondary> list = secondaryRepo.findAll(sort); 

exampletest