Hi again,
I have some trouble with calling .persist(). This will lead on the following testcase into this Exception: org.hibernate.PersistentObjectException: detached entity passed to persist: Faculty
The two comments will fix the exception but i don't like the way they to this.
Code:
public class CreateTimetableTest
{
@PersistenceContext
EntityManager entityManager;
@Test
public void shouldStoreFacultyAndGroupInTwoDifferentTransactions()
{
final Faculty f = new Faculty("Foo");
this.entityManager.persist(f);
this.entityManager.flush();
this.entityManager.clear();
// This will fix the exception by attaching the faculty again to the current session
// f = this.entityManager.find(Faculty.class, f.getId());
final Group g = new Group("Bar");
g.setFaculty(f);
f.getGroups().add(g);
// or using merge on instead of persist will fix the exception
this.entityManager.persist(g);
}
The Tests simulate the behavior of the web application. On the first Request the Faculty will stored and on the secound the new group. Thats the reason why i call Flush and Clear after persisting the Faculty.
Does anybody know how to solve this?
The Entities are quite simple:
Code:
@Entity(name = "Groups")
public class Group implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(optional = false, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH })
private Faculty faculty;
@Length(min = 1, max = 80)
private String name;
// Getter and Setter omitted
}
Code:
@Entity
public class Faculty implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = true)
@Length(min = 1, max = 80)
private String name;
@OneToMany(mappedBy = "faculty", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH, CascadeType.REMOVE })
private List<Group> groups = new ArrayList<Group>();
// Getter and Setter omitted
}