使用JPA的关系和参照完整性约束

时间:2016-10-18 11:03:23

标签: java mysql database hibernate jpa

我开始使用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提供关系和约束管理?

提前感谢!

1 个答案:

答案 0 :(得分:0)

在您的代码系统中,将按名称employee_department_mapping创建一个新表(其中包含employee_iddepartment_id列),其中包含每位员工与其部门的映射。

但是,如果要将其作为员工表中的外键处理,请使用department标记@JoinColumn字段并告知外键列的名称

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;

并将hibernate.hbm2ddl.auto设为update

现在,如果您将重新启动应用程序,它将自动按员工表中的名称department_id生成外键列。