I am using JPA 2.0 with Hibernate 4.2.5. I have bi-directional mapping to one type of object.
@OneToMany(mappedBy = "parent", cascade = { CascadeType.PERSIST, CascadeType.DETACH }, orphanRemoval = true, fetch = FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@OrderColumn(name = "position", nullable=false)
private List<MenuItem> children = new ArrayList<MenuItem>();
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinTable(name = "MenuItem_MenuItem", joinColumns = { @JoinColumn(name = "child_id") }, inverseJoinColumns = { @JoinColumn(name = "parent_id") })
private MenuItem parent;
This mapping creates the joined columns parent_id, child_id, and position. When I want to add a child to the parent, I do the following:
MenuItem newItem = service.persist(..);
parent.getChildren().add(newItem);
newItem.setParent(parent);
service.merge(newItem);
service.merge(parent);
which generates the following:
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into MenuItem (menu_id, message, messageId, params, id) values (?, ?, ?, ?, ?)
Hibernate: insert into MenuItem_MenuItem (parent_id, child_id) values (?, ?)
The problem is that the second insertion does not include the position property, so it remains zero. What am I doing wrong?
EDIT
I use spring declarative transaction management and all of my merge and save methods are annotated using @Transactional. Could this be a problem?