所以我有一个家庭实体类:
@Entity
public class Family {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "familyName")
private String familyName;
@Column(name = "externalID")
private String externalID;
public Family(String familyName) {
this.familyName = familyName;
this.externalID = UUID.randomUUID().toString();
}
}
我将仅从
FamilyDTO
获得姓氏,并将出于内部目的和数据库PK生成id
,并生成externalID
返还给客户端。现在我有一个人班:
@Entity
public class Person {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "name")
private String name;
private Integer familyID; // should be a foreign key to the family primary key id
public Project(String name) {
this.name = name;
}
}
我将从
name
中获取familyExternalID
和PersonDTO
:public class PersonDTO {
private String name;
private Integer familyExternalID;
}
现在的事情是我必须使用家庭ID作为外键,而不是使用familyexternalID(在人员表中),那么如何将familyExternalID映射到家庭表中的家庭ID,然后添加家庭ID作为外键?
最佳答案
似乎您应该在“家庭”和“人”实体之间建立关系:
@Entity
public class Person {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "name")
private String name;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "familyID")
private Family family;
public Person(String name) {
this.name = name;
}
// getters/setters...
public String getFamilyExternalID() {
if (null != this.family) {
return this.family.getExternalID();
}
return null;
}
}
至于PersonDTO,在构建DTO时,您可以使用家庭的externalID:
PersonDTO personDTO = new PersonDTO();
personDTO.setName(person.getName());
personDTO.setFamilyExternalID(person.getFamilyExternalID());
关于java - 如何从外部ID获取主键以作为外键引用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61316651/