简体   繁体   中英

JPA @ManyToMany relationship saved on only one side when database is reloaded

I'm using JPA for an application with EclipseLink and Apache Derby. I have two Entities in a @ManyToMany relationship:

@Entity
class HIT<TaskType> {
   ...
   @ManyToMany(targetEntity=Task.class, mappedBy="hits")
   protected List<TaskType> tasks = Lists.newArrayList();
}

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
abstract class Task {
    ...
    @ManyToMany(targetEntity=HIT.class)
    protected List<HIT<?>> hits = Lists.newArrayList();
}

I first create two tasks of an entity EventPresenceTask , a subclass of Task , and persist them. Later, I query the EntityManager to recover those tasks and use them to create a instance of EventPresenceHIT , a subtype of HIT . When the HIT is created, it adds both tasks to its tasks list and adds itself to the hits list of each task. It is then persisted.

After creating the objects, I check everything by first querying the EntityManager for all HIT s and printing them, then querying the EntityManager for all Task s and printing those. I get:

EventPresenceHIT{...  #tasks=2}
EventPresenceTask{... # hits=1}
EventPresenceTask{... # hits=1}

as expected. But if I close the application and reload the database, I get:

EventPresenceHIT{... #tasks=0}
EventPresenceTask{... #hits=1}
EventPresenceTask{... #hits=1}

Since everything appears to be correct in new queries to the EntityManager in the initial run of the program, I was worried that the EntityManger wasn't flushing to the database (since the program is terminated by Ctrl-C), so I put entityManager.close() in a shutdown hook to be extra safe, but it hasn't helped.

Updated : To make clear that what are being persisted and related are instances of subclasses of HIT and Task which are themselves entities.

Silly mistake - I had forgotten to annotate an inheritance strategy on the HIT class. After I did so, DB creation crashed with exceptions. However, switched to the JOINED inheritance strategy for both classes works.

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