简体   繁体   English

与同一实体的JPA关系

[英]JPA Relation with same entity

I use MYSQL, and I have employee table, contains 我使用MYSQL,并且有employee表,包含

Employee {
     id, 
     name, 
     tel, 
     dayOfBirth, 
     manager_id
} 

and the manager references to employee id, there is a database relation between the manager_id and id 并且经理引用了雇员ID,manager_id和ID之间存在数据库关系

I have create the entity class, and put relationship as following: 我已经创建了实体类,并按如下所示放置关系:

@ManyToOne(cascade = CascadeType.REFRESH, optional = false, fetch = FetchType.EAGER)
@JoinColumn(name="manager_id", nullable=true,insertable=false,updatable=true)
private Employee manager;

I need to prevent deleting the manager if he has employees. 如果经理有员工,我需要阻止删除。

your help please. 请你的帮助。

Primary way is adding restriction in SQL schema. 主要方法是在SQL模式中添加限制。

PRIMARY KEY (ID) ,
FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE(ID) 
ON DELETE NO ACTION ON UPDATE NO ACTION

In JPA you can check this using @PreDestroy 在JPA中,您可以使用@PreDestroy进行检查

public class Employee {

@PreDestory
public void preDestroy()
   ( !getEmployees().isEmpty()) {
     // handle it
   }
 }
}

I have got the solution, the solution to specify the engine as innodb as following: 我有解决方案,将引擎指定为innodb的解决方案如下:

ENGINE=INNODB ENGINE = INNODB

Thanks All 谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM