简体   繁体   中英

JPA EclipseLink @OneToMany returns empty set

I am using an embedded id:

@Embeddable
public class EntityId {
    private long id;
}

And I have the following tables:

@Entity
public class Master {
    @EmbeddedId private EntityId id;

    @OneToMany(mappedBy = "master")
    Set<Config> configs;
}

@Entity
public class SlaveLeft {
    private @EmbeddedId EntityId id;
}

@Entity
public class SlaveRight {
    private @EmbeddedId EntityId id;
}

@Entity
public class Config {

    @EmbeddedId private EntityId id;

    @ManyToOne
    @JoinColumn(name = "MASTER_ID", referencedColumnName = "id")
    private Master master;
    @ManyToOne
    @JoinColumn(name = "LEFT_ID", referencedColumnName = "id")
    private SlaveLeft slaveLeft;
    @ManyToOne
    @JoinColumn(name = "RIGHT_ID", referencedColumnName = "id")
    private SlaveRight slaveRight;
}

I then populate the database:

    final EntityManager em = injector.getInstance(EntityManager.class);
    em.getTransaction().begin();
    Master master = new Master(EntityId.next());
    SlaveLeft slaveLeft = new SlaveLeft(EntityId.next());
    SlaveRight slaveRight = new SlaveRight(EntityId.next());
    Config config = new Config(EntityId.next(), master, slaveLeft, slaveRight);

    em.persist(master);
    em.persist(slaveLeft);
    em.persist(slaveRight);
    em.persist(config);
    em.getTransaction().commit();

    final Master master1 = em.find(Master.class, master.getId());
    System.out.println(master1.getConfigs());

The problem is that the master1.getConfigs() returns empty.

What am I missing to get a working relation?

If you use another entity maneger to find your master, its configs collection will probably be populated. But here, the entity manager returns the master from its cache, and since you didn't put the config into the master's set of configs, it isn't there.

When using a bidirectional relationship, you are responsible for the maintenance of both sides of the relationship. The ORM only uses the owning side (the one without the mappedBy attribute) to decide if the relationship exists or not, but the coherence of the object graph is your responsibility.

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