简体   繁体   中英

How to use foreign id as primary id in spring boot jpa?

Is there a way to use primary key of another entity as primary key without using Embeddable or Id class. eg:

@Table(name = "employee")
@Entity
public class Employee implements Serializable {

    @Id
    @JoinColumn(name = "person_id")
    private Person person;

Here, Person is another entity and and person_id is the primary key. Thanks in advance

Yes, if this is the only paramter constructing the PK you can do it like this

public class Employee implements Serializable {

    @Id
    @Column(name="person_id")
    private Long personId;

    @JoinColumn(name = "person_id")
    private Person person;

But if this is the case there is no use of doing it, if Employee has the same primary key then they should be in the same table, no need to separate them in 2 tables.

In case we are dealing with composite primary key which contains person then we need to create an embedable key:

@Embeddable
public class CompositeKey{

   @Column(name="person_id")
   private Long personId;
   ...  // other attributes
}

public class Employee implements Serializable {

    @EmbeddedId CompositeKey employeeId;

    @JoinColumn(name = "person_id")
    private Person person;

Another note, where is your relation annotation, you should be have OneToOne annotation on your person reference :

@OneToOne
@JoinColumn(name = "person_id")
private Person person;

For me it seems that Employee could extend Person ? If this is the case then with inheritance it goes in a 'natural' way.

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Person implements Serializable {
   @Id
   @GeneratedValue
   @Getter
   private Long id;
}

@Entity
public class Employee extends Person implements Serializable {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM