从图片中,是否可以将QUALIFICATION_ID作为ID的外键而无需额外的映射列或表?
TABLE - > TM_QUALIFICATIONS 是主表,ID是自动生成的UUID,名称是String值。应用程序启动时,值将插入此表中。
TABLE - > TM_USER_QUALIFICATIONS ,一个用户可以拥有多种资格。
因此,如果没有任何其他额外的映射列或表,是否可以将QUALIFICATION_ID标记为外键?
另外,我如何组合USER_ID和QUALIFICATION_ID来为TM_USER_QUALIFICATIONS表制作复合主键?
提前致谢
答案 0 :(得分:1)
如果没有额外的列或额外的映射表,我认为你不能定义外键关系。
如果我理解正确你可以做点什么
<强> TM_QUALIFICATIONS 强>
@Entity
@Table(name = "TM_QUALIFICATIONS")
public class Qualifications {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "ID")
private String id;
@Column(name = "NAME")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
并将QUALIFICATION_ID作为外键,你可以编写单独的DDL来添加约束。
@Repository
public interface UserQualificationsRepository extends CrudRepository<UserQualifications, String>{
@Modifying
@Transactional
@Query(value = "ALTER TABLE TM_USER_QUALIFICATIONS ADD FOREIGN KEY (QUALIFICATION_ID) REFERENCES TM_QUALIFICATIONS(ID)", nativeQuery = true)
public void addForeignKeyConstraint();
}
<强> TM_USER_QUALIFICATIONS 强>
@Entity
@Table(name = "TM_USER_QUALIFICATIONS")
@IdClass(UserQualificationPK.class)
public class UserQualifications {
@Id
@Column(name = "USER_ID")
private String userId;
@Column(name = "LEVEL")
private int level = 0;
@Id
@Column(name = "QUALIFICATION_ID")
private String qualificationId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
最后,对于复合主键,使用@IdClass注释
public class UserQualificationPK implements Serializable {
private String userId;
private String qualificationId;
public UserQualificationPK(String userId, String qualificationId) {
this.userId = userId;
this.qualificationId = qualificationId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getQualificationId() {
return qualificationId;
}
public void setQualificationId(String qualificationId) {
this.qualificationId = qualificationId;
}
}
通过这种方式,你可以达到你的要求。 TM_QUALIFICATIONS和TM_USER_QUALIFICATIONS之间没有关系,但是您通过本机SQL将QUALIFICATION_ID明确定义为外键。