PersistentObjectException: detached entity passed to persist

I'm trying to do a simple persisting of an object into a MySQL database , with the following code:

publicstaticvoid main(String[] args){

EntityManager em=JPAUtility.getEntityManager();

List existing = JPAUtility.getEntityManager().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:

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

[2671 byte] By [jmutonhoa] at [2007-11-27 10:17:23]
# 1

Detached entity means - an entity having persistence identity but not associated with the current persistent context.

Check if a record already exists in database

(maybe you are not checking the case in the given query for doing this check ).

make the query case insensitive and then run?.

shivani.Eartha at 2007-7-28 15:51:25 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...