I have the following entities:
@Entity
public class Alert implements Serializable {
private long alertId;
private Set<AlertTime> alertTimes = new HashSet<AlertTime>(0);
@OneToMany(cascade = CascadeType.ALL)
public Set<AlertTime> getAlertTimes() {
return alertTimes;
}
}
And
@Entity
public class AlertTime implements Serializable {
private long alertTimeId;
private Date time;
private Alert alert;
@ManyToOne
public Alert getAlert() {
return this.alert;
}
When I need to update Alert there may be a different number of AlertTimes, so I’m trying to merge Alert and remove the AlertTimes and persist new ones. The problem with this is that there’s a unique index on (AlertTime.alertTimeId, AlertTime.time) and when I try to remove and then persist within the same transaction the SQL insert happens before the delete, which violates the constraint. I could delete the AlertTimes entities in a separate transaction, but I’d like it all to be in one transaction so I can rollback all changes if an exception occurs when calling a back-end web service.
Is there a better method to be able to change the Alert entity’s alertTimes? Or, is it possible to at least force the SQL delete before the insert?
You can flush the context with
em.flush()after removingAlertTimes to ensure thatdeletestatements was issued.Also it can be better to configure orphan removal for
alertTimes, to deleteAlertTimes from the database by removing them from the collection, without explicitremove()calls. In JPA 2.0 use@OneToMany(..., orphanRemoval = true). Though it still would requireflush().