Nimchip
Nimchip

Reputation: 1735

hibernate 3.6.7 orphanRemoval cascade unidirectional

@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "FacilityId", referencedColumnName = "Id")
@ForeignKey(name = "FK_Schedule_Facility")
@Cascade(value = {org.hibernate.annotations.CascadeType.ALL})
@OrderBy("fromDay asc")
private Set<Schedule> schedules = new HashSet<Schedule>();

I have this set in Entity Location.

In my application I construct a new set using AJAX. This has not given me any problems. I can change values in Schedules, even add more. But I CANNOT delete one. It stays in the database and in the set.

I use this method in my DAO: private SessionFactory sessionFactory;

public Facility saveOrUpdate(Facility facility){
    sessionFactory.getCurrentSession().saveOrUpdate(facility);
    return facility;
}

So I'm getting this in the log:

2013-08-06 17:44:43,444 [1219450701@qtp-169872652-2] DEBUG com.firstbankpr.os.common.data.dao.hibernate.FacilityHibernateDAO - Obtaining Session
2013-08-06 17:44:43,450 [1219450701@qtp-169872652-2] WARN  org.hibernate.util.JDBCExceptionReporter - SQL Error: 515, SQLState: 23000
2013-08-06 17:44:43,450 [1219450701@qtp-169872652-2] ERROR org.hibernate.util.JDBCExceptionReporter - Cannot insert the value NULL into column 'FacilityId', table 'OLS.dbo.Schedule'; column does not allow nulls. UPDATE fails.

After entering nullable = false in the joinColumn annotation, the error goes away. But it still does not correctly remove the Schedule I want to remove.

So what am I doing wrong? I've done a lot of googling. Found bugs in Hibernate 3.5 which do not apply to me since i'm using 3.6.7. Found that hashcode and equals have to be implemented correctly and found that JPA and Hibernate annotations often clash with each other. I've also found that bi-directional relations have problems with cascading, but again it does not apply to me. But aside from all those searches, I haven't quite found a solution for this one. Or perhaps I'm overlooking something.

Please help me out and thank you!

Upvotes: 0

Views: 955

Answers (1)

Pace
Pace

Reputation: 43887

For some reason saveOrUpdate() doesn't properly process delete-orphans. You have to call merge() instead.

Upvotes: 1

Related Questions