0

detached entity passes to persist error in hibernate/jpa with same example on this link.

public static void main(String[] args){
         UserBean user = new UserBean();
         user.setId(1);
         user.setUserName("name1");
         user.setPassword("passwd1");
         em.persist(user);
  }

caused due to: setting id explicitly

The question is why has this entity become detached ? From my understanding when you create a new entity it is transient and when you try to persist it ,it becomes persistent. So how can the entity become detached since detached entity is it not currently in the persistent context but in the database?

Help and Correct me if I am wrong somewhere.

Community
  • 1
  • 1
Milind Vinkar
  • 159
  • 1
  • 9

1 Answers1

0

As the error message says, if you create a new object, you should not set the id.

public static void main(String[] args){
         UserBean user = new UserBean();
         user.setUserName("name1");
         user.setPassword("passwd1");
         em.persist(user);
  }

If you want to change one object which is already persist, you have to read it first from the db and then change the attribute an update the object

Jens
  • 67,715
  • 15
  • 98
  • 113
  • but when a new object of the entity is created ,it wont have any record in the database but still we can call persist over that object. Then how can it be an update? And if the id is different then object will be considered different then why not just save it as new record if there is no clash in ids? – Milind Vinkar Jul 22 '16 at 05:18
  • 1
    @MilindVinkar it is an update, because the object has already an id – Jens Jul 22 '16 at 05:21