[英]How to combine distinct and sort in spring data jpa specification query with joins
示例设置:
实体
@Entity
class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null
@ManyToMany(cascade = [CascadeType.PERSIST, CascadeType.MERGE])
@JoinTable(name = "book_authors",
joinColumns = [JoinColumn(name = "book_id")],
inverseJoinColumns = [JoinColumn(name = "author_id")])
var authors: MutableSet<Author> = HashSet()
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "publisher_id")
lateinit var publisher: Publisher
}
Author 和 Publisher 都是简单的实体,只有一个 id 和一个名称。
spring 数据 jpa BookSpecification:(注意查询的不同)
fun hasAuthors(authorNames: Array<String>? = null): Specification<Book> {
return Specification { root, query, builder ->
query.distinct(true)
val matchingAuthors = authorRepository.findAllByNameIn(authorNames)
if (matchingAuthors.isNotEmpty()) {
val joinSet = root.joinSet<Book, Author>("authors", JoinType.LEFT)
builder.or(joinSet.`in`(matchingContentVersions))
} else {
builder.disjunction()
}
}
}
执行查询(可分页包含对publisher.name 的排序)
bookRepository.findAll(
Specification.where(bookSpecification.hasAuthors(searchRequest)),
pageable!!)
REST 请求:
MockMvcRequestBuilders.get("/books?authors=Jane,John&sort=publisherName,desc")
这会导致以下错误:
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Order by expression "PUBLISHERO3_.NAME" must be in the result list in this case;
问题在于distinct 和sort 的组合。 不同的要求发布者名称位于选择字段中才能进行排序。
如何使用规范查询解决此问题?
您可能必须像这样明确选择PUBLISHERO3_.NAME
列:
query.select(builder.array(root.get("PUBLISHERO3_.NAME"), root.get("yourColumnHere")));
默认情况下可能不包括连接的列,因为它们超出了根泛型类型的范围。
你不能这样做。 基本上,如果您有不同的并且想要排序,则只能使用选定的列。
您可以做的是使用row_number()
窗口函数而不是distinct
,然后使用row_number=1
选择所有内容。 你可以在这里找到一个(有点老)的例子: https : //stackoverflow.com/a/30827497/10668681
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.