Cascade persist does not observe correct order and fails

Description

Persisting an entity fails sometimes with CascadeType.PERSIST option. This is the case when the order of persisting entities is important. Example:

Container

 

– Element -----------------|

Association
-- Opposite Element --------


Persisting Container should persists in the given order:
1. Element
2. Opposite Element
3. Association (depends on element an opposite)

Testing this scenario with Hibernate sometimes works and sometimes fails. Same code works fine with EclipseLink as JPA provider.

In order to reproduce the problem create three entities: Container, Element, Association.
Test Case:

final Container container = new Container();
final Element element = new Element();
container.addElement(element);

final Opposite opposite = new Element();
container.addElement(opposite);

final Association association = new Association(element, opposite);
em.persist(container);

@Entity
public class Container {
...
@OneToMany(mappedBy = "container", cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
private Collection<Element> elements = new HashSet<Element>();
...
}

@Entity
public class Element {
...
@ManyToOne(optional = false)
@JoinColumn(name = "container_id", referencedColumnName = "id")
private Container container;

@OneToMany(mappedBy = "element", cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
private Collection<Association> outgoing = new HashSet<Association>();

@OneToMany(mappedBy = "opposite", cascade = { CascadeType.REMOVE })
private Collection<Association> incoming = new HashSet<Association>();
...
}

@Entity
public class Association {
...
public Association(final Element element, final Element opposite) {
this.element = element;
this.opposite = opposite;
element.addOutgoingAssociation(this);
opposite.addIncomingAssociation(this);
}

@ManyToOne(optional = false)
@JoinColumn(name = "element_id", referencedColumnName = "id")
private Element element;

@ManyToOne(optional = false)
@JoinColumn(name = "opposite_id", referencedColumnName = "id", unique = false)
private Element opposite;
...
}

Environment

None

Activity

Show:
Steve Ebersole
March 21, 2011, 7:08 PM

Bulk closing stale resolved issues

Assignee

Gail Badner

Reporter

Ralf Pöhlmann

Fix versions

None

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

Priority

Blocker
Configure