如何动态地订购与JPA或HQL的多对多关系? [英] How to dynamically order many-to-many relationship with JPA or HQL?

查看:147
本文介绍了如何动态地订购与JPA或HQL的多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的映射:

@ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(
            name="product_product_catalog",
            joinColumns={@JoinColumn(name="product_catalog", referencedColumnName="product_catalog")},
            inverseJoinColumns={@JoinColumn(name="product", referencedColumnName="product")})
    public List<Product> products = new ArrayList<Product>();

我可以很好地获取目录产品,但我不能(动态)订购产品。
我怎么订购它们?
我可能不得不用order-by子句写一个多对多的HQL查询?我将orderBy字段名称字符串传递给查询,还是有更好的解决方案?

I can fetch the products for the catalog nicely, but I can't (dynamically) order the products. How could I order them? I probably have to write a many-to-many HQL query with the order-by clause? I though of passing the orderBy field name string to the query, or is there a better solution?

表格是:
products,
product_catalog,
product_product_catalog(关联表)

Tables are: products, product_catalog, product_product_catalog (associative table)

PS使用Play!我的实体的框架JPASupport。

P.S. Using Play! Framework JPASupport for my entities.

推荐答案


我可以很好地获取目录产品,但我不能(动态)订购产品。我怎么能订购它们?

I can fetch the products for the catalog nicely, but I can't (dynamically) order the products. How could I order them?

如果让JPA检索关联,则不可能。映射是静态的,使用映射可以做的最好的事情是在检索时间指定顺序:

Not possible if you let JPA retrieve the association. Mappings are static, the best thing you can do with mappings is to specify the order at "retrieve time":


9.1.28 OrderBy注释



OrderBy 注释指定检索关联时集合值关联元素的排序。

9.1.28 OrderBy Annotation

The OrderBy annotation specifies the ordering of the elements of a collection valued association at the point when the association is retrieved.

@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OrderBy {
   String value() default "";
}

订购
元素的值的语法是 orderby_list ,因为
如下:

The syntax of the value ordering element is an orderby_list, as follows:

orderby_list::= orderby_item [,orderby_item]*
orderby_item::= property_or_field_name [ASC | DESC]

如果未指定ASC或DESC,则假定为ASC(升序)。

If ASC or DESC is not specified, ASC (ascending order) is assumed.

如果未指定排序元素,则假定按关联实体的主键排序。

If the ordering element is not specified, ordering by the primary key of the associated entity is assumed.

该属性或字段名称必须与关联类的持久属性或字段的名称相对应。订购中使用的属性或字段必须与支持比较运算符的列相对应。

The property or field name must correspond to that of a persistent property or field of the associated class. The properties or fields used in the ordering must correspond to columns for which comparison operators are supported.

示例:

@Entity public class Course {
  ...
  @ManyToMany
  @OrderBy("lastname ASC")
  public List<Student> getStudents() {...};
  ...
}


所以要么使用自定义查找器,要么使用比较器从Java中对列表进行排序。

So either use a custom finder or sort your list from Java using a Comparator.

这篇关于如何动态地订购与JPA或HQL的多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆