以下关系创建外键映射
@Entity
public class Department {
@Id
private String name;
//some more fields
}
@Entity
public class Employee {
@Id
private long id;
private String name;
private String designation;
@ManyToOne
@JoinColumn(name = "fk_department_id", foreignKey = @ForeignKey(name="fk_department"))
private Department department;
}
生成:
... CONSTRAINT
fk_department
外键(fk_department_id
)参考department
(name
)
问题:如何在无需创建Department
实体的休眠 中触发此约束创建?
例如,仅添加外键@Id
字段而无需显式实体引用。但是仍然在初始创建时触发fk。以下当然是无效的:
@ManyToOne
@JoinColumn(name = "fk_department_id", foreignKey = @ForeignKey(name="fk_department"))
private String department;
您明白了。有可能吗?
(旁注:我对通过启动ddl / sql语句创建该外键链接不感兴趣)。
答案 0 :(得分:1)
您至少要删除@ManyToOne
,因为这是针对实体的。
以下内容应通过覆盖列定义以在创建外键时将其包括在内而起作用
@Column(name = "department_id", columnDefinition = "VARCHAR(255), foreign key (department_id) REFERENCES department(name)")
private String department;
现在只定义了一个列和一个约束,但是实体之间没有定义任何关系(据Hibernate所知)。
本质上是从Hibernate and JPA: how to make a foreign key constraint on a String复制而来的,但是很难找到,所以我不只是将其作为副本关闭! ;)