Many to One Relationship While removing child object it's throwing exception

人盡茶涼 提交于 2019-12-02 02:50:39

问题


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.


回答1:


 @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST}, fetch=FetchType.EAGER)

The above code will resolve your issue. If you observe source code of annotation ManyToOne it has an array of cascade type so you can map multiple cascade types




回答2:


You should not use CascadeType.ALL, try using CascadeType.MERGE

The meaning of CascadeType.ALL is that the persistence will propagate (cascade) all EntityManager operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.

It seems in your case to be a bad idea, as removing an Project would lead to removing the related Company when you are using CAscadeType.ALL. As a Company can have multiple projects, the other projects would become orphans. However the inverse case (removing the Company) would make sense - it is safe to propagate the removal of all projects belonging to a Company if this company is deleted.

You can also use various CascadeTypes, for e.g. cascade = {CascadeType.PERSIST,CascadeType.MERGE}. So use all those that applied to you.

For more info.




回答3:


You got MySQLIntegrityConstraintViolationException. It means there are tables in the database you're binding. You should map when you set up the many to one relationship tables. Company should be able to get more than one project. So you have to define the list of projects.

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
@JoinColumn(name="companyId")
private Company company;

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;

@OneToMany(mappedBy="company", fetch=FetchType.EAGER)
private List<Project> projects;


来源:https://stackoverflow.com/questions/21545682/many-to-one-relationship-while-removing-child-object-its-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!