0

我需要从数据库中获取一些数据。为此,我编写了类似的代码

try{
   return (EmployeeImpl) em.createQuery(
      "select e from EmployeeImpl e " +
      "where e.empName = :employeeName " + 
          " and (e.eDate is null or e.eDate <=   :todaysDate )")
 .setParameter("employeeName", employeeName)
 .setParameter("todaysDate", todaysDate)
 .getSingleResult();
}catch(NoResultException exception){
     throw new NoResultException("Record not found");
}

我应该返回一份有效记录。但给出了例外

org.hibernate.util.JDBCExceptionReporter] 事务未激活:tx=TransactionImple < ac, BasicAction: 0:ffff0a5308fa:126a:4fb36c77:559 状态:ActionStatus.ABORT_ONLY >; - 嵌套 throwable:(javax.resource.ResourceException:事务未激活:tx=TransactionImple < ac,BasicAction:0:ffff0a5308fa:126a:4fb36c77:559 状态:ActionStatus.ABORT_ONLY >)

 org.hibernate.exception.GenericJDBCException: Cannot open connection

javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Cannot open connection

我的应用程序可以连接到数据库,因为我可以在其他地方执行 CRUD 操作。

此异常的可能原因是什么。

4

3 回答 3

1

根本原因:数据不可用

getSingleResult() 抛出空指针异常,而 getResultList() 返回空,是根据您在查询中传递的条件找到零记录的情况。尝试更换: -

catch(NoResultException exception){
     throw new NoResultException("Record not found");
}

catch(NoResultException exception){
    throw new NoResultException("Record not found");
}
catch(Exception ex){
    ex.printStackTrace();
}

我相信你会在日志中得到 NullPointerException。简而言之,这个完整的跟踪应该得到:-

SQL Error: 0, SQLState: null
Transaction is not active: tx=TransactionImple < ac, BasicAction: 0:ffffa9b67064:126a:58924abe:14bb957 status: ActionStatus.ABORT_ONLY >; - nested throwable: (javax.resource.ResourceException: Transaction is not active: tx=TransactionImple < ac, BasicAction: 0:ffffa9b67064:126a:58924abe:14bb957 status: ActionStatus.ABORT_ONLY >)
org.hibernate.exception.GenericJDBCException: Cannot open connection

这清楚地说明了您的交易被中止的方式和原因。

于 2017-03-16T10:04:49.790 回答
0

The reason seems clear:

org.hibernate.exception.GenericJDBCException: Cannot open connection

For whatever reason, the code you posted is unable to acquire a connection while other parts of your application (according to what you've posted) are able to do so fine. I would check to make sure that this part of the code is not configured differently, using a different method for getting connections, etc.

于 2012-05-16T13:44:38.830 回答
0

在实际执行任何数据库操作,如插入、更新或选择之前,您应该首先启动一个事务(当然是在获取会话对象之后)。然后你应该做任何 CRUD 操作。请确保您在执行查询之前开始交易。

于 2012-05-16T19:15:08.460 回答