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

六月ゝ 毕业季﹏ 提交于 2019-12-02 01:03:17
 @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

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.

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