找不到查询异常的实体,即使该查询有一行

时间:2018-10-04 14:40:04

标签: hibernate jpa

我写了一个简单的程序来登录用户。我可以从表中获取所有结果,并且可以正常工作,但是当我想检查是否存在具有名称和密码的用户时,总是找不到查询异常的实体,我知道是表中具有该名称和密码的行。 这是我的代码:

public List<Person> getList(){
    return entityManager.createQuery("select entity from person entity").getResultList();
}
public Person logIn(String name,String password){
      String selectQuery = "select entity from person entity where name=:name and password=:password";
      Person person = (Person)entityManager.createQuery(selectQuery)
              .setParameter("name",name)
              .setParameter("password",password)
              .getSingleResult();

      System.out.println(person);
      return person;
}

这是我的Person实体类

@Entity(name = "person")
    @Table(name = "PERSON")
public class Person {
    @Id
    @Column(name = "ID",columnDefinition = "NUMBER")
    @SequenceGenerator(name = "PERSON_SEQ",sequenceName = "PERSON_SEQ",allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.AUTO,generator = "PERSON_SEQ")
    private Long id;
    @Column(name = "NAME",columnDefinition = "NVARCHAR2(30)")
    @NotNull(errorCode = "Null",message = "Name can't be null")
    @NotEmpty(errorCode = "Empty",message = "Name can't be empty")

    private String name;

    @Column(name = "FAMILY",columnDefinition = "NVARCHAR2(30)")
    @NotNull(errorCode = "Null",message = "Family can't be null")
    @NotEmpty(errorCode = "Empty",message = "Family can't be empty")
    private String family;

    @Column(name = "Password",columnDefinition = "VARCHAR2(256)")
    @NotNull(errorCode = "Null",message = "Family can't be null")
    @NotEmpty(errorCode = "Empty",message = "Family can't be empty")
    private String password; /*setter and getter methods....*/

2 个答案:

答案 0 :(得分:1)

我认为Person必须是驼色的,如下所示:

select entity from Person entity

答案 1 :(得分:0)

如果有多行,则方法getSingleResult()可能抛出NonUniqueResultException。因此,除非您的表中有唯一的约束,否则将来可能会发生这种情况。

还要确保使用try/catch块来知道您是否有结果:

      String selectQuery = "select entity from person entity where name=:name and password=:password";
      Person person = null;

      try{
       person = (Person)entityManager.createQuery(selectQuery)
              .setParameter("name",name)
              .setParameter("password",password)
              .getSingleResult();
      }
      catch(NoResultException e){
        //TO-DO do something if query retrieves nothing
      }       

      System.out.println(person);
      return person;

否则,您始终可以使用上述方法getResultList()并只需调用get(0)就可以得到第一个结果。

如果您确实认为查询返回了一行,请再次检查您的sql语句。

编辑:

您可以尝试使用本机查询

    String selectQuery = "SELECT * FROM PERSON where name = ?1 and password = ?2";

    Query q = em.createNativeQuery(selectQuery);
    q.setParameter(1, name);
    q.setParameter(2, password);

    person = (Person) q.getSingleResult();