0

I have 2 class

public class User {
     @Id
     @Column(name = "id")
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
     private String name;
     private String age;
     @OneToOne
     @JoinColumn(name = "address_id", referencedColumnName = "id")
     private Address address;
}

and

public class Address {
     @Id
     @Column(name = "id")
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
     private String building;
     private String country;
     @OneToOne(mappedBy = "address")
     private User user;
}

in my table address, I have a few rows.
When I insert table user with data

{
   "id":null,
   "name":"Foo",
   "age":"18",
   "address":{
      "id":1,
      "building":"Too",
      "country":"ABS"
   }
}

Table user have 1 row with address_id =1.
I insert same data as above
Table user have 2 row with address_id =1.
My answer is: why 2 table connected by one to one can happen the above case?

sourab maity
  • 1,025
  • 2
  • 8
  • 16
QuangVu
  • 27
  • 1
  • 10

1 Answers1

0

You can find your answer here Why @OneToOne is allowing duplicate associations?

Basically, @JoinColumn(name = "address_id", referencedColumnName = "id") alone doesn't serve the semantics of one-to-one in the database, you need to add unique=true into the @JoinColumn, which makes it @JoinColumn(name = "address_id", referencedColumnName = "id", unique = true).

Side-note: I suggest you drop your tables and then re-creating them before trying this out. If you are using Hibernate, you can set hibernate.hbm2ddl.auto to create-drop

Ngọc Hy
  • 298
  • 1
  • 6
  • 15