Issue
I have the following tables,
User
int id PK
Contact
int id PK, FK to User.id
So my code in Contact.java
is as follows,
@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
@Id
@Column(name = "id", insertable = false, updatable = false)
private Integer id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "id", nullable = false)
private User userId;
In my User.java
it has,
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
So according to the above code, I have some questions.
Is that the correct approach to indicate that id(primary key) of Contact is also a foreign key to User?
And do I need to use
@PrimaryKeyJoinColumn
or@JoinColumn
?According to the above code how my repository interface should be?
public interface ContactRepository extends JpaRepository<Contact, User> {}
or
public interface ContactRepository extends JpaRepository<Contact, Integer> {}
Solution
- Don't use foreign key as primary key, if use can
- JoinColumn
- Contract has Integer id, so
<Contact, Integer>
Answered By - Micah