小编nie*_*ame的帖子

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

示例设置:

实体

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

java spring-data spring-data-jpa kotlin

7
推荐指数
1
解决办法
1138
查看次数

标签 统计

java ×1

kotlin ×1

spring-data ×1

spring-data-jpa ×1