Java持久性 - getSingleResult()没有检索任何实体

时间:2014-02-05 23:11:57

标签: java oracle jpa oracle11g

我正在测试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

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

1 个答案:

答案 0 :(得分: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");
}