0

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

MGorgon
  • 2,547
  • 23
  • 41
  • My bet is because `thisSameAddress` is a detached entity at the time you `.setAddress` I think the code is behaving exactly how it should, (the single entry in `ADRESS` shows that `Cust c` has the address because it was persisted after b... If you want to see an exception, then commit the transaction on `em.persist(b)` and then do `em.persist(c)` – j.con Sep 02 '14 at 19:22
  • Still no exception, both custs are persisted with this same address. – MGorgon Sep 02 '14 at 19:28

1 Answers1

1

Possible duplicate of http://stackoverflow.com/questions/8968294/why-onetoone-is-allowing-duplicate-associations It looks like @OneToOne does not enforce unique constraints

j.con
  • 879
  • 7
  • 19