Alex Parker
Alex Parker

Reputation: 1583

JPA -- Multiple ManyToMany Lists of the same type in one Entity

I have a class that contains two Lists. Both lists are of the same type. The relationship for both lists is many-to-many.

@Entity
@Table(name = "task_instance")
public class TaskInstance {
    ...
    @ManyToMany
    private List<ScriptExecutableOrder> preScriptExecutables;

    @ManyToMany
    private List<ScriptExecutableOrder> postScriptExecutables;
    ...
}

A join table is created automatically that looks like this: Join table for TaskInstance and ScriptExecutableOrder

However, when I use the getter methods to retrieve the Lists (i.e., getPreScriptExecutables() and getPostScriptExecutables()), the Lists are out of order. Through debugging, I have determined this: when the Lists are set, the order is consistent. I can set the Lists and get them, and the order is as epxected. Yet, when the EntityManager is closed, apparently the order is confounded. When a new EntityManager is opened and the getter is used to retrieve the Lists, the objects are ordered by the ScriptExecutableOrders' ids. Opening a new EntityManager is when the order is lost completely, even though the MySQL table is still in the appropriate order.

I have also tried creating separate join tables using the @JoinTable annotation. However, this didn't solve the problem.

I assume that somehow the way that I am setting up the entities and tables is causing this discrepancy, but I cannot figure it out. I am completely new to JPA.

Upvotes: 1

Views: 1150

Answers (1)

Alex Parker
Alex Parker

Reputation: 1583

I figured it out. I used the @JoinTable annotation for both Lists (preScriptExecutables and postScriptExecutables), and then I added the @OrderColumn annotation like this

@OrderColumn(name = "list_index")

for both Lists. This created a column that would serve for ordering purposes.

Upvotes: 1

Related Questions