简体   繁体   中英

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: TaskInstance和ScriptExecutableOrder的联接表

However, when I use the getter methods to retrieve the Lists (ie, 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.

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.

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