Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate JPA分离对象正在持久化_Hibernate_Jpa - Fatal编程技术网

Hibernate JPA分离对象正在持久化

Hibernate JPA分离对象正在持久化,hibernate,jpa,Hibernate,Jpa,我正在使用JPA1.0 hibernate实现和MySql数据库 project=em.find(Project.class,projectTO.getProjectID()); System.out.println("after find "+em.contains(project)); 当find返回托管状态对象时打印true em.detach(project); System.out.println("after detach "+em.contains(project)); 打印f

我正在使用JPA1.0 hibernate实现和MySql数据库

project=em.find(Project.class,projectTO.getProjectID());
System.out.println("after find "+em.contains(project));
当find返回托管状态对象时打印true

em.detach(project);
System.out.println("after detach "+em.contains(project));
打印false,因为对象现在处于分离状态

em.getTransaction().begin();
em.persist(project);
在这里,我试图持久化一个分离的对象。因此,它应该给出一个非法的例外。但在这里,它给出了MySQLIntegrityConstraintViolationException,因为它试图持久化一个已经存在的数据

System.out.println("after persist "+em.contains(project));
当对象处于托管状态时,它打印为true

em.getTransaction().commit();
所以我的问题是为什么分离的对象会持久化?
为什么我得不到文件上的非法州例外

看看下面的persist方法规范:

/**
 * 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将尝试持久化它,并将该实体作为一个新实体处理。

该实体是如何定义的?它是否有生成的ID@GeneratedValue?它是否有版本字段@version?如果没有这些,Hibernate将无法将分离的对象与临时对象区分开来。@JBNizet我没有将任何注释用作@GeneratedValue或@Version。在这种情况下,正如我所说的,Hibernate无法区分ID为56的分离的、已经持久的实体和要插入ID为56的临时实体。既然您调用了persist,它就假定它是暂时的,并尝试插入它。@JBNizet那么我应该怎么做来纠正它呢。?你能详细说明一下“区分瞬时物体和分离物体”吗?我给你一个物体。您如何知道它是否存在于数据库中?如果将ID配置为自动生成,则可以执行以下操作:如果对象具有ID,则该对象存在于数据库中。如果不是,则是要插入的新对象。如果Hibernate分配了一个版本字段,则可以选择:如果版本为0,则从未插入。如果没有,则已插入。如果这两个都没有,你就不知道了。由于调用persist,您的目的是在数据库中插入一个新对象。所以Hibernate就这样做了,但是失败了,因为它已经存在了。