gpt4 book ai didi

java - getFirstResult() 返回 0

转载 作者:行者123 更新时间:2023-11-29 05:06:00 24 4
gpt4 key购买 nike

我最近在做 Java 教程,但遇到了查询问题。起初我将人员添加到数据库。

图片 1: enter image description here

图片 2: enter image description here

现在,当我查询此人是否在场时,get firstResult() 返回零 :/。

Person 类示例,带有查询:

@Entity
@NamedQuery(name="findQuery", query="select p from Person p where p.id=:id")
public class Person {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
//@Column(name="personId")
private long id;
//@Column(name="personName")
private String name;
//@Column(name="personAge")
private int age;
//@Column(name="personNumber")
private int number;

现在检查查询的类:

@Override
public String read(long id) {


TypedQuery<Person> createNamedQuery = em.createNamedQuery("findQuery", Person.class);
createNamedQuery.setParameter("id", id);

int firstResult = createNamedQuery.getFirstResult();
System.out.println("test: "+firstResult);

if (createNamedQuery.getFirstResult()>0) {
Person singleResult = createNamedQuery.getSingleResult();
creationMessage = "User: " + singleResult.getName() + " added to database with success";
} else {
creationMessage = "User was not added to database";
}
return creationMessage;
}

当我尝试查找 ID 为 1 的人时,getFirstResult 返回零:/。有人可以帮助我吗,我做错了什么?

我不知道告诉它是否重要,但数据源是 JTA。 :)

最佳答案

来自 Query#getFirstResult() 的 Javadoc :

The position of the first result the query object was set to retrieve. Returns 0 if setFirstResult was not applied to the query object

您从未调用过 setFirstResult,因此 getFirstResult 应该返回零。我怀疑您将此方法混淆为可以检测是否存在匹配记录的方法。相反,为此使用以下代码:

TypedQuery<Person> createNamedQuery = em.createNamedQuery("findQuery", Person.class);
createNamedQuery.setParameter("id", id);
try {
Person singleResult = createNamedQuery.getSingleResult();
creationMessage = "User: " + singleResult.getName()+" added to database with success";
}
catch (Exception e) {
System.out.println("Either less than one row, more than one row, or some other error");
}

getSingleResult() 如果没有找到用户记录,或者如果找到多个记录,将抛出异常。通过捕获异常,您可以确定查询是否成功。迭代结果集通常以这种方式工作;您一次阅读一份记录,并在阅读过程中弄清楚事情。

关于java - getFirstResult() 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48059775/

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