简体   繁体   English

如何使用JPA或HQL动态订购多对多关系?

[英]How to dynamically order many-to-many relationship with JPA or HQL?

I have a mapping like this: 我有这样的映射:

@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>();

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? 我可能不得不用order-by子句写一个多对多的HQL查询? I though of passing the orderBy field name string to the query, or is there a better solution? 我虽然将orderBy字段名称字符串传递给查询,还是有更好的解决方案?

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

PS Using Play! PS使用播放! Framework JPASupport for my entities. 我的实体的框架JPASupport。

I can fetch the products for the catalog nicely, but I can't (dynamically) order the products. 我可以很好地获取目录的产品,但我不能(动态)订购产品。 How could I order them? 我怎么能订购它们?

Not possible if you let JPA retrieve the association. 如果让JPA检索关联,则不可能。 Mappings are static, the best thing you can do with mappings is to specify the order at "retrieve time": 映射是静态的,使用映射可以做的最好的事情是在“检索时间”指定顺序:

9.1.28 OrderBy Annotation 9.1.28 OrderBy注释

The OrderBy annotation specifies the ordering of the elements of a collection valued association at the point when the association is retrieved. OrderBy注释指定在检索关联时的集合值关联的元素的排序。

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

The syntax of the value ordering element is an orderby_list , as follows: 值排序元素的语法是orderby_list ,如下所示:

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

If ASC or DESC is not specified, ASC (ascending order) is assumed. 如果未指定ASC或DESC,则假定ASC(升序)。

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. 排序中使用的属性或字段必须对应于支持比较运算符的列。

Example: 例:

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

So either use a custom finder or sort your list from Java using a Comparator . 因此,无论是使用自定义取景器或使用从Java排序列表Comparator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM