使用 javax.persistence.OrderBy 注释时是否可以通过策略定义自定义订单?
从文档中我知道我们可以指定一列,但是有没有办法传入自定义比较器并根据该列进行排序?
所以它可能看起来像这样:
@OneToMany(cascade=CascadeType.ALL)
@OrderBy("createdDateTime", comparator=StripYearComparator.class)
public List<A> getAs() {
return result;
}
有人有和我一样的用例吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道@Tommy。 @OrderBy 的全部要点是定义数据库(或其他数据存储)如何完成排序。它转换为 SQL 查询(或其他一些请求),如下所示。
数据不会由驱动程序或其他实体在客户端上检索和排序,因此无法注入您自己的比较器。
如果您需要替代的排序策略,那么恐怕您将不得不将这些项目检索到代码中并自己对它们进行排序。
Not that I know of @Tommy. The whole point of the
@OrderBy
is to define how the sorting is being done by the database (or other datastore). It translates into a SQL query (or some other request) like as the following.The data is not retrieved and then sorted on the client by the driver or some other entity so there is no way to inject your own comparator.
If you need an alternative sorting strategy then I'm afraid you are going to have to retrieve the items into your code and sort them yourself.
@Gray感谢您的建议,我用不同的方法解决了问题,并认为我可以分享它。
我们将 JSF 与 Richfaces 3.1.6GA 一起使用。最初,我希望 JPA 层返回已订购的列表以馈送到 Richfaces 中。我们发现,在 Richfaces 3.2 及更高版本中,sortBy 功能已融入标签中。您只需指定一种排序方法即可。所以我的解决方案是升级到较新版本的 Richfaces 并在我的实体类中添加以下方法。
因此,在我的 Person 类中,
我有一个方法 getNamesWithoutCommas() ,顾名思义,它获取不带逗号的名称,然后使用它进行排序。
在声明我的专栏时,我有这样的内容:
@Gray thanks for the advice, I solved the problem with a different approach and thought I might share it.
We are using JSF with Richfaces 3.1.6GA. Originally I wanted the JPA layer to return the listed already ordered to feed into Richfaces. What we found was that in Richfaces 3.2 and above the functionality of sortBy in baked into the tag. All you have to specify is a method in which you want to sort by. So my solution was to upgrade to a newer version of Richfaces and add the following method in my entity class.
So in my Person class,
I have a method getNamesWithoutCommas() which as the name implies gets the name without the commas and then use that to sort.
In declaring my column I have something like this: