Hey.
working with hibernate core versin - 3.3.6GA
i tried to remove element (element number -2) from detached collection and merge the container.
there was strange behaviour with differents annotation.
in bidirectional i update both sides.
case 1- bidirectional without delete orphans:
dosnt delete.
case 2- bidrectional with delete orphan and in the many side cascade all:
delete the collection and the container
case 3- bidrectional with delete orphan and cascade in the many side:
delete element 2 from the database - the expected behaviour.
code:
Code:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int id;
@OneToMany(cascade=CascadeType.ALL)
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public Collection<Permission> permissions = new LinkedList<Permission>();
}
@Entity
public class Permission {
private static int counter = 0;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int id;
@Column
public int name;
@ManyToOne()
@JoinColumn(name="user_fk")
public User user;
}
public static void main(String[] args) {
// Start EntityManagerFactory
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("test");
// First unit of work
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
User u = new User();
for (int i = 1; i < 5; i++) {
Permission p = new Permission();
p.user = u;
p.name = i;
u.permissions.add(p);
}
u = em.merge(u);
tx.commit();
em.close();
// second unit of work
EntityManager em2 = emf.createEntityManager();
EntityTransaction tx2 = em2.getTransaction();
tx2.begin();
for (Iterator iterator = u.permissions.iterator(); iterator.hasNext();) {
Permission permission = (Permission) iterator.next();
if(permission.id == 2){
permission.user = null;
iterator.remove();
}
}
u = em2.merge(u);
tx2.commit();
em2.close();
emf.close();
}