Nikita Kalugin
Nikita Kalugin

Reputation: 742

JPA: @PrimaryKeyJoinColumn or @JoinColumn + @Id

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?

Upvotes: 2

Views: 9662

Answers (2)

mtshaikh
mtshaikh

Reputation: 668

As @Entity must always have an @Id, you could use the following snippet to map the both entities

@Id
@Column(name="user_id")
private Long id;

@OneToOne (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name="user_id", referencedColumnName="user_id")
private User user;

Upvotes: 7

Andronicus
Andronicus

Reputation: 26036

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).

Upvotes: 2

Related Questions