开发者

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 Con开发者_如何学JAVAfig {

    @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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜