[英]Spring JPA : @OrderBy doesn't work when using saveAndFlush
I am using @OrderBy
clause on my bean this works fine when i am getting this object from the persistence layer, but when i try to save this data using我在我的 bean 上使用
@OrderBy
子句,当我从持久层获取这个对象时,这工作正常,但是当我尝试使用
persistedObject = saveAndFlush(MyCustomObject);
Results in persistedObject
are not sorted as specified by @OrderBy
clause. persistedObject
中的结果未按照@OrderBy
子句的指定进行排序。
Code snippet :代码片段:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "COLLECTION_ID")
@OrderBy("order ASC")
private Set<MySections> sections;
class MySections {
// Some Properties
@Column(name = "SEQ_NO")
private Integer order;
}
Repository related code存储库相关代码
// this brings sections ordered by order property
collectionRepository.findById("123");
// Sections in persistedCollection are not ordered
persistedCollection = collectionRepository.saveAndFlush(collection);
It's because @OrderBy
does not materialize the order directly in database.这是因为
@OrderBy
没有直接在数据库中实现订单。 It fetches the data and performs sorting in memory.它获取数据并在内存中执行排序。 To achieve, what you have described you would have to use
@OrderColumn
.要实现您所描述的内容,您必须使用
@OrderColumn
。 It maintains the persistent order of rows in database.它维护数据库中行的持久顺序。
One more advice - using just select
queries is not a good option to check for ordering as database does not assure about the ordering of the result.还有一个建议 - 仅使用
select
查询不是检查排序的好选择,因为数据库不能保证结果的排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.