7

How do we achieve unidirectional @OneToOne Mapping between two entities with @JoinColumn to apply on target entity.

For E.g. I have two entities:

   @Entity
   public class Person {

      // Attaches column in the source entity i.e. Person
      @OneToOne
      @JoinColumn(name = "Person_ID")
      private Address address;

      //Works for @oneToMany, attaches column in target entity i.e. Address
      @OneToMany
      @JoinColumn(name = "Person_ID")
      private Set<Address> addresses;  
   }

   @Entity
   public class Address {
     //list of columns
   }

As per documentation: http://docs.oracle.com/javaee/6/api/javax/persistence/JoinColumn.html

If the join is for a OneToOne or ManyToOne mapping using a foreign key mapping strategy, the foreign key column is in the table of the source entity or embeddable.

If the join is for a unidirectional OneToMany mapping using a foreign key mapping strategy, the foreign key is in the table of the target entity.

sandy.sm
  • 175
  • 5
  • 14
  • I don't understand a question where you present both options available in JPA. You have the OneToMany mapping, create accessors that only return a single instance, and your database constraint can be configured to make "person_id" unique. Or are you looking outside of JPA? – Chris Sep 26 '16 at 19:10
  • I wanted OneToOne mapping, Looking for an option where I could attach foreign key column to the target entity (which happens in OneToMany).. Either way I could keep reference of Person in Address entity. Having OneToMany with accessors to return a single instance is not a good idea for me. – sandy.sm Sep 27 '16 at 04:11
  • 2
    Did you ever find a proper solution for this? I ran into the same issue and I can't see a reason why JPA would not allow to define such a mapping (i.e. @OneToOne with joincolumn in target entity table), but I have a feeling there might be one. – Tobias Meyer Aug 22 '17 at 16:17
  • This is an excellent question – MetaColon Nov 09 '18 at 14:53

0 Answers0