我正在尝试使用异常来处理用户输入的名称长度超过一定字符数的情况。如果发生异常,我会将其捕获为 PersistenceException 并向用户提供信息。
EntityManagerFactory emf=(EntityManagerFactory)getServletContext().getAttribute("emf");
EntityManager em = emf.createEntityManager();
try
{
String name = request.getParameter("name");
if(name != null)
{
em.getTransaction().begin();
em.persist(new Guest(name));
em.getTransaction().commit();
}
...
}
catch(PersistenceException e)
{
request.setAttribute("valid", false);
}
但是在通知用户之后,我仍然需要列出之前输入到 db 的所有名称,但在以下片段中:
finally
{
List<Guest> guests= em.createQuery("SELECT g FROM Guest g",Guest.class).getResultList(); }
我得到:
org.hibernate.AssertionFailure: null id in com.guest.Guest entry (don't flush the Session after an exception occurs)
当我通过重新创建实体管理器将“最后”部分更改为以下时,我不会收到错误。
finally{
em = emf.createEntityManager();
List<Guest> guests= em.createQuery("SELECT g FROM Guest....}
我还使用 Eclipse 调试器检查了 EntityManager 是否正常,得到以下结果:
那么,即使我的 EntityManager 没问题,为什么我需要再次创建它才能不出现该错误?
最佳答案
If the Session throws an exception, including any SQLException, immediately rollback the database transaction, call Session.close() and discard the Session instance. Certain methods of Session will not leave the session in a consistent state. No exception thrown by Hibernate can be treated as recoverable.
关于java - 异常后丢失EntityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31997395/