user1680859
user1680859

Reputation: 1194

Java persistence - getSingleResult() did not retrieve any entities

I am testing a JPA project as follows:

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");
        }

The output is:

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

The qry string is:

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

When I test directly in SQLPLUS:

SELECT a, b FROM C##test.testcon

it gives me the correct result. I can not find out where the program fails.

Upvotes: 1

Views: 6470

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

Create a transaction before executing the query.

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");
}

Upvotes: 1

Related Questions