0

How to use the primary key defined in one @Entity class in another @Entity class in @OneToOne relationship in hibernate

Till now I've this...I do not want to use @Id in phoneNumber of the Phone class. How to do that? And are @JoinColumn and @MapsId annotations mandatory(what do they exactly do)? Thank you all.

@Entity
public class User {
    @Id
    private int id;
    private String name;
    @OneToOne
    private Phone phone;
...
}
@Entity
public class Phone {
    private int phoneNumber;
    @OneToOne
    @JoinColumn(name="id")
    @MapsId
    private User user;
...
}

Edited: while mapped to tables, I want the table Phone to have a column that is a primary key for itself while being the same value as that of the primary key of table User.

robinhoodjr
  • 415
  • 8
  • 20
  • kinda hard to tell what you want to achieve... Try to rephrase the question / make an example of what you want – Zeromus May 29 '19 at 10:09
  • If you don't want to use `@Id` in `Phone`, does that then mean that phone records in your database should not have identity? Why don't you then just add a phone field to a user? – M. Prokhorov May 29 '19 at 10:13
  • [@MapsId](https://stackoverflow.com/questions/9923643/can-someone-please-explain-me-mapsid-in-hibernate). `@JoinColumn` seems to be used right. No you can't do what you want. You always need `@Id` – XtremeBaumer May 29 '19 at 10:13
  • @Zeromus added a brief statement to make it clearer. – robinhoodjr May 29 '19 at 10:13
  • @XtremeBaumer I want id but not from the member variables of Phone class should be the same as that of User class – robinhoodjr May 29 '19 at 10:15
  • @robinhoodjr, "i want id of Phone to be the same as that of User" - you can't do that if your user has several phones. It's called Id for a reason - its value should be unique in any given table. – M. Prokhorov May 29 '19 at 10:17
  • @M.Prokhorov damn I've gone insane. It's 5 in the morning.if it we're onetoone, how to achieve this? – robinhoodjr May 29 '19 at 10:21
  • @robinhoodjr, `@MapsId` already means primary key is shared, itsn't it? Speaking from having read this: https://stackoverflow.com/questions/9923643/can-someone-please-explain-me-mapsid-in-hibernate – M. Prokhorov May 29 '19 at 10:25
  • @M.Prokhorov thanks. I need some rest and fresh pair of eyes, it seems. – robinhoodjr May 29 '19 at 10:28
  • Perhaps reading up on the hibernate framework and how it works will answer the answer the question ' are `@JoinColumn `and `@MapsId` annotations mandatory(what do they exactly do)?'. – J_D May 29 '19 at 11:24

0 Answers0