示例设置:
实体
@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)