Strange JPA one-to-many behavior when trying to set the "many" on the "one" entity

Posted by errr on Stack Overflow See other posts from Stack Overflow or by errr
Published on 2010-06-15T10:50:03Z Indexed on 2010/06/15 10:52 UTC
Read the original article Hit count: 225

I've mapped two entities using JPA (specifically Hibernate). Those entities have a one-to-many relationship (I've simplified for presentation):

@Entity
public class A {

    @ManyToOne
    public B getB() { return b; }
}

@Entity
public Class B {

    @OneToMany(mappedBy="b")
    public Set<A> getAs() { return as; }
}

Now, I'm trying to create a relationship between two instances of these entities by using the setter of the one-side/not-owner-side of the relationship (i.e the table being referenced to):

em.getTransaction().begin();

A a = new A();
B b = new B();
Set<A> as = new HashSet<A>();
as.add(a);
b.setAs(as);

em.persist(a);
em.persist(b);
em.getTransaction().commit();

But then, the relationship isn't persisted to the DB (the row created for entity A isn't referencing the row created for entity B). Why is it so? I'd excpect it to work.

Also, if I remove the "mappedBy" property from the @OneToMany annotation it will work. Again - why is it so? and what are the possible effects for removing the "mappedBy" property?

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about jpa