我开始使用 MySQL 和 JPA 来设计我的 Java EE 应用程序以实现持久性,因此我怀疑它在数据库设计中的实现程度。
所以我定义了我的数据库表,例如:员工和部门与他的关系
我使用 JPA 根据一些教程定义了关系,但我不明白是否也必须为数据库表定义外键和约束,或者不定义为:
CREATE TABLE `thejavageek`.`employee` (
`idemployee` INT NOT NULL,
`firstname` VARCHAR(45) NULL,
`lastname` VARCHAR(45) NULL,
# ...
PRIMARY KEY (`idemployee`)
);
和 JPA 实体:
@Entity
public class Employee{
@Id
@GeneratedValue( strategy= GenerationType.AUTO )
private int eid;
private String ename;
private double salary;
private String deg;
@ManyToOne
private Department department;
public Employee(int eid, String ename, double salary, String deg) {
super( );
this.eid = eid;
this.ename = ename;
this.salary = salary;
this.deg = deg;
}
public Employee( ) {
super();
}
public int getEid( ) {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname( ) {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSalary( ) {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDeg( ) {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
@Entity
public class Department {
@Id
@GeneratedValue( strategy=GenerationType.AUTO )
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName( ){
return name;
}
public void setName( String deptName ){
this.name = deptName;
}
}
将关系和约束管理留给 JPA?
提前致谢!
最佳答案
在您的代码系统中,将创建一个名为 employee_department_mapping
的新表(其中包含 employee_id
、department_id
列),其中包含一个映射每个员工到其部门。
但是,如果你想把它作为employee表的外键来处理,用@JoinColumn
标记你的department
字段,并告诉外键列的名字
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
并将hibernate.hbm2ddl.auto
设置为update
现在,如果您重新启动应用程序,它将在员工表中自动生成名称为 department_id 的外键列。
关于java - 使用 JPA 的关系和参照完整性约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40106500/