0

I have two entities User and Contact . User object contains the Contact. How do I use JPA annotations so that when I save User object , the contact table should have Users's id as its primaryKey ?

            Public class User{
            public String username;
            public long id;
            public Contact contact;

            }

            public class Contact {
            public long id;
            public string phone;
            public string email;
            }
Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
user1493834
  • 756
  • 4
  • 11
  • 25
  • possible duplicate of [JPA @OneToOne with Shared ID -- Can I do this Better?](http://stackoverflow.com/questions/6833370/jpa-onetoone-with-shared-id-can-i-do-this-better) – Oleg Mikheev Nov 25 '14 at 04:49

1 Answers1

0

Something similar to this

@Entity  
public class User{
    @Column
    public String username;
    @Id
    public long id;
    @OneToMany(mappedBy="id")
    public Contact contact;

}

@Entity 
public class Contact {
    @Id
    public long id;
    @Column
    public string phone;
    @Column
    public string email;
}
Junaid
  • 2,572
  • 6
  • 41
  • 77
  • that did not work. I think we have to use something @PrimaryKeyJoinColumn as shown here (http://www.techferry.com/articles/hibernate-jpa-annotations.html#OneToOne). ..but after I implement this way my contact id is diff than the user id. – user1493834 Nov 25 '14 at 06:00
  • This is just for giving you an idea, its not the complete solution. – Junaid Nov 25 '14 at 06:03
  • I need OnetoOne mapping with user's id existing as foreign key in the contact table. – user1493834 Nov 25 '14 at 15:04