gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:44 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于Java 持久性 - getSingleResult() 未检索任何实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21590633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com