Hazim Eid
Hazim Eid

Reputation: 835

JPA Relation with same entity

I use MYSQL, and I have employee table, contains

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

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.

Upvotes: 1

Views: 97

Answers (2)

Hazim Eid
Hazim Eid

Reputation: 835

I have got the solution, the solution to specify the engine as innodb as following:

ENGINE=INNODB

Thanks All

Upvotes: 0

vels4j
vels4j

Reputation: 11298

Primary way is adding restriction in SQL schema.

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

public class Employee {

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

Upvotes: 1

Related Questions