Issue
I have user class with @Entity annotation.
@Entity
public class User{
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
}
And i need to create another table with User details.
It must be linked to User_id and don't have it's own id just:
user_id
phone_number
address
So, now i use this:
@Entity
@Table
@Data
public class UserDetails{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Long id;
@OneToOne (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private User user;
private String address;
private String phone;
}
But i have a question: Why i use this:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Long id;
if
@OneToOne (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private User user;
makes user_id for me?
If i delete Id field i have an error: No identifier specified for entity: test.UserDetails, but hey! @PrimaryKeyJoinColumn creates identifier for this entity.
Maybe i should use @Id + @JoinColumn instead of @PrimaryKeyJoinColumn?
Solution
It's just a part of the specification. @Entity
always must have an @Id
. In this example you don't even need (strategy = GenerationType.IDENTITY)
as the key is given by parent entity (so there is no need to use any strategy for it's generation).
Answered By - Andronicus