I'm getting this error when I build my Application:
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: model.Student
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124) [hibernate-core-5.0.7.Final.jar:5.0.7.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58) [hibernate-core-5.0.7.Final.jar:5.0.7.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775) [hibernate-core-5.0.7.Final.jar:5.0.7.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748) [hibernate-core-5.0.7.Final.jar:5.0.7.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753) [hibernate-core-5.0.7.Final.jar:5.0.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146) [hibernate-entitymanager-5.0.7.Final.jar:5.0.7.Final]
... 190 more
I have to add that, when I use merge(std) instead of persist(std). Than i have no problem which is also weird.
Thats my Entity class with GeneratedValue --> GenerationType.AUTO):
@Entity
@NamedQueries({@NamedQuery(name = Student.QRY_GET_STUDENTS, query = "select s from Student s")})
public class Student {
public static final String QRY_GET_STUDENTS = "studentQuery";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Size(min = 3, max = 70)
private String name;
@Size(min = 7, max = 7, message = "Matrikelnummer muss 7 Ziffern haben!")
private String matriculationNumber;
@DecimalMax(value = "5.0", message = "Note muss zwischen 1.0 und 5.0 sein!")
private double note;
private String lecture;
}
Thats my persistence class:
@Stateless
@Transactional
public class StudentPersistence {
@PersistenceContext(unitName = "UniPortalDS")
private EntityManager em;
public List<Student> getStudent() {
return (List<Student>) em.createNamedQuery("studentQuery").getResultList();
}
public List<Student> saveAllStudentsPersistence(@Nonnull Student std) {
TypedQuery<Student> q = em.createNamedQuery(std.QRY_GET_STUDENTS, Student.class);
em.persist(std);
return q.getResultList();
}
}
Finally thats my service class:
@Stateless
public class StudentService {
@EJB
private StudentPersistence studentPersistence;
public List<Student> getStudent() {
return studentPersistence.getStudent();
}
//Jetzt -->
public void saveStudentsNew(@Nonnull Student std) {
studentPersistence.saveAllStudentsPersistence(std);
}
}