如何通过联接将Spring Data JPA规范查询中的区分和排序结合在一起
来源:爱站网时间:2021-09-16编辑:网友分享
示例设置:实体@Entity类图书{@Id @GeneratedValue(strategy = GenerationType.IDENTITY)var id:长? = null @ManyToMany(级联= [CascadeType.PERSIST,CascadeType.MERGE] ...
问题描述
示例设置:
实体
@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 = HashSet()
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "publisher_id")
lateinit var publisher: Publisher
}
作者和发布者都是具有ID和名称的简单实体。
spring data jpa BookSpecification:(注意查询上的不同)
fun hasAuthors(authorNames: Array? = null): Specification {
return Specification { root, query, builder ->
query.distinct(true)
val matchingAuthors = authorRepository.findAllByNameIn(authorNames)
if (matchingAuthors.isNotEmpty()) {
val joinSet = root.joinSet("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;
问题在于区别和排序的结合。唯一性要求发布者名称在选择字段中才能排序。
如何通过规格查询解决此问题?
解决方法:
您可能必须像下面这样显式选择PUBLISHERO3_.NAME
列:
query.select(builder.array(root.get("PUBLISHERO3_.NAME"), root.get("yourColumnHere")));
默认情况下可能不包括联接的列,因为它们在根通用类型方面超出范围。