getFirstResult()返回0

时间:2018-01-02 11:02:32

标签: java mysql jpa jpql

我最近正在做一个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。 :)

2 个答案:

答案 0 :(得分:1)

来自Query#getFirstResult()的Javadoc:

  

查询对象设置为检索的第一个结果的位置。如果未将setFirstResult应用于查询对象

,则返回0

您从未致电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()将抛出异常。通过捕获异常,您可以确定查询是否成功。迭代结果集通常以这种方式工作;你一次读一条记录,并随着时间的推移弄清楚事情。

答案 1 :(得分:0)

我认为你应该尝试重构一下你的解决方案,因为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(NoResultException e) { creationMessage = "User was not added to database"; } 主要用于分页目的,而不是你想要的东西。

更自然的方法是获得单个结果,如果找不到任何内容则捕获和异常:

CREATE OR REPLACE FUNCTION fn_trgr() RETURNS trigger AS
  $BODY$
    DECLARE
      val_c TEXT;
      val_b TEXT;
    BEGIN
    SELECT DISTINCT col_b INTO val_b FROM table_1 WHERE col_a=NEW.col_a;
    SELECT DISTINCT col_c INTO val_c FROM table_1 WHERE col_a=NEW.col_a;

    NEW.col_b := val_b ;
    NEW.col_c := val_c ;

    RETURN NEW;
    END;
  $BODY$
LANGUAGE plpgsql