I'm trying to do a simple persisting of an object into a MySQL database , with the following code:
Code:
public static void main(String[] args){
EntityManager em=JPAUtility.getEntityManager();
List existing =em.createQuery("select u from UserBean u where u.userName='foo' and u.password='bar'").getResultList();
if (existing.size() == 0) {
System.out.println("User not in db...inserting");
UserBean user = new UserBean();
JPAUtility.beginTransaction();
user.setId(1);
user.setUserName("foo");
user.setPassword("bar");
em.persist(user);
JPAUtility.commitTransaction();
System.out.println("Persisted user "+user.getUserName());
} else {
System.out.println("Already in db...");
}
}
When I run this I'm getting a org.hibernate.PersistentObjectException: detached entity passed to persist .The full stacktrace is as follows:
Code:
User not in db...inserting
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.introspect.tutorial.UserBean
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:629)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:218)
at com.introspect.tutorial.JPAUtility.main(JPAUtility.java:172)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.introspect.tutorial.UserBean
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:79)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:212)
... 1 more