简体   繁体   中英

Maintain an order with a OneToMany join

I'm using spring boot and want to add a list of products to a page as a foreign key but how can I maintain the ArrayList order when I retrieve from the database? Should I have an intermediate table eg PageProductOrder which maintains product primary key and order column?

@Entity
public class Page {
    @OneToMany
    @JoinColumn(name = "product_id")
    private List<Product> products;

You could do this by using @OrderColumn - this will use a column in the entity for ordering :

@OneToMany
@JoinColumn(name = "product_id")
@OrderColumn(name = "product_index")
private List<Product> products;

The column product_index in Product entity will be used for maintaining order.

You can define the order by using the @OrderBy annotation.

@OneToMany
@JoinColumn(name = "product_id")
@OrderBy(value = "name ASC")
private List<Product> products;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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