Hibernate version:
Hibernate Core 3.3.0.CR1
Hibernate EntityManager 3.4.0.CR1
Hibernate Annotations 3.4.0.CR1
Problem:
I have table organisation and table permission. Table permission is because one organisation can have permissions to do some work for different organisations.
Here is code for those classes wo getters and setters:
Code:
@Entity
public class Organisation {
@Id
@GeneratedValue
Long id;
String name;
@OneToMany(mappedBy = "orgType1", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
List<Permission> permList;
public void addPermToList(Permission p) {
if (permList == null) {
permList = new ArrayList<Permission>();
}
permList.add(p);
}
}
@Entity
public class Permission {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Organisation orgType1;
@ManyToOne
private Organisation orgType2;
String permission;
public Permission(Organization o1, Organization o2, String perm) {
orgType1 = o1;
orgType2 = o2;
permission = perm;
}
}
Now I have organisation o1 and o2 and I want to add to o1 permission to o2. (emf = Persistence.createEntityManagerFactory("testEM");)
Code:
EntityManager em = emf.createEntityManager();
Organization o1 = em.find(Organization.class, new Long(1));
Organization o2 = em.find(Organization.class, new Long(2));
Permission p1 = new Permission(o1, o2, "perm");
em.getTransaction().begin();
//begin
o1.addPermToList(p1);
em.merge(o1);
//end
em.getTransaction().commit();
em.close();
This block of code adds 2 exactly the same records in table permission and the question is why?
I made more examples, I have changed the code between comments
begin and
end to those:
Code:
1)
o1.addPermToList(p1);
em.persist(o1);
2)
em.persist(o1);
o1.addPermToList(p1);
3)
em.merge(o1);
o1.addPermToList(p1);
and each of these works as I desired (adds 1 record in permission table).
Of course I can always persist permission, but i also want to make some changes to o1 such as add a user who modified the organization and therefore I thought merge(o1) would be the best....
Probably I am missing something, but can't figure it out.