如何将spring数据jpa规范查询中的distinct和sort与join结合起来

nie*_*ame 7 java spring-data spring-data-jpa kotlin

示例设置:

实体

@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
}
Run Code Online (Sandbox Code Playgroud)

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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

执行查询(可分页包含对publisher.name 的排序)

bookRepository.findAll(
    Specification.where(bookSpecification.hasAuthors(searchRequest)),
    pageable!!)
Run Code Online (Sandbox Code Playgroud)

REST 请求:

MockMvcRequestBuilders.get("/books?authors=Jane,John&sort=publisherName,desc")
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Order by expression "PUBLISHERO3_.NAME" must be in the result list in this case;
Run Code Online (Sandbox Code Playgroud)

问题在于distinct 和sort 的组合。不同的要求发布者名称位于选择字段中才能进行排序。

如何使用规范查询解决此问题?

whi*_*row 0

您可能必须PUBLISHERO3_.NAME像这样显式选择列:

query.select(builder.array(root.get("PUBLISHERO3_.NAME"), root.get("yourColumnHere")));
Run Code Online (Sandbox Code Playgroud)

默认情况下可能不包含连接列,因为它们超出了根泛型类型的范围。