Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Order in hibernate

I have 4 entities:

Profile which has a relation with companyContract:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "profile", cascade = { CascadeType.ALL })
@Fetch(value = FetchMode.SUBSELECT)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
private List<CompanyContract> companyContracts;

CompanyContract which has a relation with timesheet:

@OneToMany(mappedBy = "companyContract", cascade = { CascadeType.ALL },orphanRemoval = true, fetch = FetchType.EAGER)
@Fetch(FetchMode.SUBSELECT)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
private List<Timesheet> timesheets;

    @ManyToOne
@JoinColumn(name = "IDPROFILE")
private Profile profile;

Timesheet which has a relation with invoice:

@OneToMany(mappedBy = "timesheet", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
private List<Invoice> invoices;

@ManyToOne
@JoinColumn(name = "IDCONTRACT")
private CompanyContract companyContract;

Invoice:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_TIMESHEET")
private Timesheet timesheet;

So As you can see here, I'm using org.hibernate.annotations.CascadeType.DELETE_ORPHAN so I can delete the children of a parent.

If I execute this:

Profile p = companyContract.getProfile();
p.getCompanyContracts().remove(companyContract);
companyContract.setProfile(null);
profileService.update(p);

---> The order of removal should be:

Remove invoices --> Timesheets --> CompanyContract, No ?

And instead I'm getting this error:

org.hibernate.exception.ConstraintViolationException: Column 'IDCONTRACT' cannot be null

And I've checked, this error happens after profileService.updateProfile(p);

like image 643
Moatez Bouhdid Avatar asked Sep 25 '17 15:09

Moatez Bouhdid


1 Answers

The problem seems to be that the column IDCONTRACTin the table that holds Timesheets has a NOT NULL restriction. Remove it and try again.

If you're autogenerating the schema, try adding @Basic(optional = true) to Timesheet.companyContract:

@Basic(optional = true)
@ManyToOne
@JoinColumn(name = "IDCONTRACT")
private CompanyContract companyContract;
like image 89
Martín Straus Avatar answered Oct 22 '22 13:10

Martín Straus