Hibernate JPA分离对象是持久化的

时间:2014-08-19 20:20:56

标签: hibernate jpa

我使用JPA 1.0(hibernate实现)和MySql数据库。

project=em.find(Project.class,projectTO.getProjectID());
System.out.println("after find "+em.contains(project));

打印 true ,因为find()会返回托管状态对象。

em.detach(project);
System.out.println("after detach "+em.contains(project));

打印 false ,因为对象现在处于分离状态

em.getTransaction().begin();
em.persist(project);

我试图坚持一个分离的物体。所以它应该给出 IllegalStateException 。但是在这里,它正在尝试保留现有数据,因为它正在提供 MySQLIntegrityConstraintViolationException

System.out.println("after persist "+em.contains(project));

当对象处于托管状态时,它会打印true

em.getTransaction().commit();

所以我的问题是为什么分离对象会被持久化? 为什么我没有根据文件获得IllegalStateException

1 个答案:

答案 0 :(得分:0)

看看下面的持久方法规范:

/**
 * Make an entity instance managed and persistent.
 * @param entity
 * @throws EntityExistsException if the entity already exists.
 * (The EntityExistsException may be thrown when the persist
 * operation is invoked, or the EntityExistsException or
 * another PersistenceException may be thrown at flush or commit
 * time.)
 * @throws IllegalStateException if this EntityManager has been closed.
 * @throws IllegalArgumentException if not an entity
 * @throws TransactionRequiredException if invoked on a
 * container-managed entity manager of type
 * PersistenceContextType.TRANSACTION and there is
 * no transaction.
 */
public void persist(Object entity);

如果EntityManager关闭,该方法应该只抛出IllegalStateException。由于您的ID属性具有值且对象在持久性范围之外,因此JPA将尝试将其保留,将实体作为新实体处理。