我們有一個與另一個物體有多對多關系的父物體(洗掉了不相關的屬性)以及該物體的相應存盤庫。有沒有辦法按孩子排序?
例如:我使用 sortBy 'category1' 發送請求,父物體按子物體的聚合值排序,按 value 屬性聚合,并且僅使用相應的類別。我嘗試添加自定義 Postgres 方言并使用 select string_agg 但我無法進行排序。我們正在使用彈簧排序和分頁。鑒于以下父物體鏈接到子物體,發送請求以獲取具有排序列“category1”和排序順序“降序”的父物體,它應該嘗試按“aaabbb”和“cccddd”對父物體進行排序并回傳 parent2 , 父母 1。
{
name: 'parent1',
child: [
{
category: 'category1',
value: 'aaa'
},
{
category: 'category1',
value: 'bbb'
},
{
category: 'category2',
value: 'ccc'
}
]
}
{
name: 'parent2',
child: [
{
category: 'category1',
value: 'ccc'
},
{
category: 'category1',
value: 'ddd'
},
{
category: 'category2',
value: 'eee'
}
]
}
@Entity(name = "parent")
class ParentEntity {
@field:ManyToMany(fetch = FetchType.EAGER)
@field:ValidateCategories([category1, category2, category3])
val child: MutableSet<ChildEntity>
}
@Entity(name = "child")
@Table(uniqueConstraints = [UniqueConstraint(columnNames = ["category", "value"])])
class ChildEntity {
@field:Column(nullable = false)
@field:Enumerated(EnumType.STRING)
val category: Category
@field:Column(nullable = false, columnDefinition = "citext")
@field:Size(min = 1, max = 255)
val value: String
}
interface ParentRepository : JpaRepository<ParentEntity, String> {
@Query(
value = "select distinct pe as ParentEntity, lower(pe.name), lower(pe.description) from parent pe left join pe. child c1 on c1.category = 'category1'
left join pe.child c2 on c2.category = 'category2' left join pe.child c3 on c3.category = 'category3' where etc....)
fun findByProperties(
@Param("request") request: GetRequest,
pageable: Pageable
): Page<ParentEntityProjection>
uj5u.com熱心網友回復:
最后,我們能夠通過執行以下操作來解決此問題:
擴展 postgres 方言(注意必須使用,在 application.properties 檔案中更改以下屬性spring.jpa.properties.hibernate.dialect)
class PostgresRichDialect : PostgreSQL10Dialect() {
init {
registerFunction("string_agg", SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(?1, ?2)"))
registerFunction(
"string_agg",
SQLFunctionTemplate(
StandardBasicTypes.STRING,
"string_agg(?1, ?2 ORDER BY ?3 )"
)
)
}
}
更新查詢如下:
@Query(
value = "select distinct pe as ParentEntity, lower(pe.name), lower(pe.description), string_agg(c1.value, ',', c1.value) as cValue from parent pe left join pe. child c1 on c1.category = 'category1'
left join pe.child c2 on c2.category = 'category2' left join pe.child c3 on c3.category = 'category3' where etc.... group by pp.id)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490063.html
上一篇:這怎么會有回圈依賴?
