lennard
lennard

Reputation: 563

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 e.g. PageProductOrder which maintains product primary key and order column?

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

Upvotes: 6

Views: 3714

Answers (2)

Michał Krzywański
Michał Krzywański

Reputation: 16910

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.

Upvotes: 9

Michael
Michael

Reputation: 1184

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

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

Upvotes: 4

Related Questions