【发布时间】:2020-06-06 02:17:48
【问题描述】:
设置示例:
实体
@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 和 name 的简单实体。
spring data 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 的组合。 distinct 要求发布者名称位于选择字段中才能进行排序。
如何使用规范查询解决此问题?
【问题讨论】:
标签: java kotlin spring-data-jpa spring-data