I have a department table having below structure
Field Type Null Key Default Extra
id int(11) NO PRI auto_increment
name varchar(45) NO UNI
description varchar(100) YES
Note that id is auto_increment(auto number) and the database that I'm using is MySQL.
During insert, if I provide the the value for id it takes that id and inserts a record. Below statement insert a record with id=9.
insert into department values(9, "dept09", "department 09");
If I do not provide the value for id, it takes the next value and inserts a record. In this case id would be 10 . Below statement inserts a record with id=10.
insert into department(dept_name, description) values("dept10", "department 10");
My Department class in Java looks like below. I'm using hibernate/JPA as persistence provider I'm using GenerationType.IDENTITY as strategy to generate the identifier for the object.
@Entity
public class Department {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String description;
....
}
I'm persisting department as below:
// create and persist an Department
em.getTransaction().begin();
Department dept = new Department();
dept.setId(13);
dept.setName("dept13");
dept.setDescription("Department 13");
em.persist(dept);
em.getTransaction().commit();
Since I'm providing the value for id as 13, I'm expecting that a record with id=13 would be persisted in database, but hibernate/JPA is giving the error below:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.mycompany.app.Department
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1152)
at com.mycompany.services.DepartmentService.createDepartment(DepartmentService.java:21)
Why is it saying the newly created department as detached entity? If I comment out "dept.setId(13)", it works fine and a department with (max id value in DB)+1 as id value.