如何在spring boot jpa中使用外部id作为主id?

时间:2017-12-18 09:32:10

标签: java mysql spring hibernate jpa

有没有办法在不使用Embeddable或Id类的情况下将另一个实体的主键用作主键。 e.g:

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

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

这里,Person是另一个实体,person_id是主键。 提前致谢

2 个答案:

答案 0 :(得分:5)

是的,如果这是构建PK的唯一参数,你就可以这样做

"dialogAction": {
    "type": "Close",
    "fulfillmentState": "Fulfilled or Failed",
    "message": {
      "contentType": "PlainText or SSML",
      "content": "Message to convey to the user. For example, Thanks, your pizza has been ordered."
    },
   "responseCard": {
      "version": integer-value,
      "contentType": "application/vnd.amazonaws.card.generic",
      "genericAttachments": [
          {
             "title":"card-title",
             "subTitle":"card-sub-title",
             "imageUrl":"URL of the image to be shown",
             "attachmentLinkUrl":"URL of the attachment to be associated with the card",
             "buttons":[ 
                 {
                    "text":"button-text",
                    "value":"Value sent to server on button click"
                 }
              ]
           } 
       ] 
     }
  }

但是如果是这种情况就没有用它,如果Employee具有相同的主键,那么它们应该在同一个表中,不需要在2个表中将它们分开。

如果我们正在处理包含person的复合主键,那么我们需要创建一个可嵌入的键:

public class Employee implements Serializable {

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

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

另一个注意事项,你的关系注释在哪里,你应该在你的人物参考上有OneToOne注释:

@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;

答案 1 :(得分:1)

对我来说,似乎Employee可以延长Person?如果是这种情况,那么通过继承它会进入一个自然的'方式。

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

@Entity
public class Employee extends Person implements Serializable {

}