I am doing Many To One relationship using JPA . While deleting child object from Child table it's throwing exception.
Below is My code:
Project.java
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="projectName")
private String projectName;
@Column(name="projectDesc")
private String projectDesc;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="companyId")
Company.java
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="compName")
private String compName;
@Column(name="address")
private String address;
Below is Insert code:
InserAction.java
public static void main(String[] args) {
Company comp2 = new Company();
comp2.setCompName("IBM");
comp2.setAddress("Bangalore");
Project pro2 = new Project();
pro2.setProjectName("Management System");
pro2.setProjectDesc("System");
pro2.setCompany(comp2);
EntityManager entityManager = EntityManagerUtil.getEmf().createEntityManager();
try{
EntityTransaction entr = entityManager.getTransaction();
entr.begin();
entityManager.persist(pro2);
entr.commit();
}
}
DeleteAction.java
EntityManager entityManager = EntityManagerUtil.getEmf()
.createEntityManager();
try {
EntityTransaction entr = entityManager.getTransaction();
entr.begin();
Project project = entityManager.find(Project.class,5);
entityManager.remove(project);
entr.commit();
}
Exception is
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`prabha`.`project`, CONSTRAINT `FK_project_companyId` FOREIGN KEY (`companyId`) REFERENCES `company` (`id`))
Error Code: 1451
Call: DELETE FROM company WHERE (id = ?)
bind => [1 parameter bound]
Query: DeleteObjectQuery(com.demo.manytoone.Company@301db5ec)
While deleting project object from Project table it' throwing above exception how can I over come this.