【问题标题】:Java persistence - getSingleResult() did not retrieve any entitiesJava 持久性 - getSingleResult() 没有检索到任何实体
【发布时间】:2014-02-05 23:11:56
【问题描述】:

我正在测试一个 JPA 项目,如下所示:

try {
            emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
            EntityManager em = emFactory.createEntityManager();
            Query qry = em.createQuery("select t from TestCon t");
            System.out.println(qry);
            TestCon tcon = (TestCon) qry.getSingleResult(); //qry.getSingleResult();
            rslt = tcon.getB();
            if (rslt == null || rslt.equals(""))
                rslt = "Could not get result";
            System.out.println(rslt); //new ShowMsg(rslt);
        } catch (Exception ex) {
            System.out.println(ex); //new ShowMsg("Exception occured");
        }

输出是:

javax.persistence.NoResultException: getSingleResult() did not retrieve any entities.

qry 字符串是:

EJBQueryImpl(ReadAllQuery(referenceClass=TestCon sql="SELECT a, b FROM C##test.testcon"))

当我直接在 SQLPLUS 中测试时:

SELECT a, b FROM C##test.testcon

它给了我正确的结果。我找不到程序失败的地方。

【问题讨论】:

  • 表格中的记录不止一条吗?
  • 您应该ex.printStackTrace() 以获取更多信息。

标签: java oracle jpa oracle11g


【解决方案1】:

在执行查询之前创建一个事务。

try {
    emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = emFactory.createEntityManager();

    em.getTransaction().begin(); //added

    Query qry = em.createQuery("select t from TestCon t");
    System.out.println(qry);

    //need to use getResultList() if table has > 1 row
    List<TestCon> tcon = (List<TestCon>) qry.getResultList();

    for(Testcon rslt:tcon){ 
         rslt = tcon.getB();
         if (rslt == null || rslt.equals("")){
             rslt = "Could not get result";
         }
         System.out.println(rslt); //new ShowMsg(rslt);
    }

    entityManager.getTransaction().commit(); //added
    entityManager.close(); //added
} catch (Exception ex) {
 System.out.println(ex); //new ShowMsg("Exception occured");
}

【讨论】:

  • @user1680859 很高兴我能帮上忙!
猜你喜欢
  • 2011-02-06
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多