I've read that OneToOne mapping is "relationship in Java is where the source object has an attribute that references another target object and (if) that target object had the inverse relationship back to the source object it would also be a OneToOne relationship." source: http://en.wikibooks.org/wiki/Java_Persistence/OneToOne
Based on above, I assume that one table can reference another with cardinality equal to (zero) one, and this one can inverse reference first table with this same cardinality (zero) one.
So, I have created this simple entities (Cust can have one Adress, and Adress can have one Cust)
@Entity
public class Cust {
@Id
@GeneratedValue
private Long id;
private String desc;
@OneToOne(fetch = FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.REMOVE})
@JoinColumn(name="adress_fk")
private Adress adress;
//getters, setters...
@Entity
public class Adress {
@Id
@GeneratedValue
private Long id;
private String val1;
private String val2;
@OneToOne(mappedBy = "adress")
private Cust b;
//getters, setters...
I was curious what will happen when I'll try to persist two custs with this same adress. I wrote sample code to give a try:
Adress thisSameAddress = new Adress();
thisSameAddress.setVal1("blabla");
thisSameAddress.setVal2("nlanla");
Cust b = new Cust();
b.setAdress(thisSameAddress );
b.setDesc("asdasd");
Cust c = new Cust();
c.setAdress(thisSameAddress );
c.setDesc("eeee");
tx.begin();
em.persist(b);
em.persist(c);
tx.commit();
I was expecting some exception when trying to persist two custs with this same address. However, code ran and in database I can see one Adress and Two Custs:
SELECT * FROM CUST;
ID DESC ADRESS_FK
1 asdasd 1
2 eeee 1
SELECT * FROM ADRESS;
ID VAL1 VAL2
1 a c
Why JPA allowed for this kind of operation? This behaves like it is Many (Cust) to One (Adress) relationship..
JPA implementation is 4.3.6 Final and DB is H2 1.4.181