javax.persistence.NoResultException: No entity found for query

后端 未结 6 1541
再見小時候
再見小時候 2020-12-08 04:11

Before I posted this question, I already looked this, but I couldn\'t get what I was looking for.

I know that for the query I wrote there may exist only one row or n

相关标签:
6条回答
  • 2020-12-08 04:23

    You mentioned getting the result list from the Query, since you don't know that there is a UniqueResult (hence the exception) you could use list and check the size?

    if (query.list().size() == 1) 
    

    Since you're not doing a get() to get your unique object a query will be executed whether you call uniqueResult or list.

    0 讨论(0)
  • 2020-12-08 04:27

    When using java 8, you may take advantage of stream API and simplify code to

    return (YourEntityClass) entityManager.createQuery()
    ....
    .getResultList()
    .stream().findFirst();
    

    That will give you java.util.Optional

    If you prefer null instead, all you need is

     ...
    .getResultList()
    .stream().findFirst().orElse(null);
    
    0 讨论(0)
  • 2020-12-08 04:32

    Another option is to use uniqueResultOptional() method, which gives you Optional in result:

    String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
    Query query=em.createQuery(hql);
    query.setParameter("today",new LocalDate());
    
    Optional<DrawUnusedBalance> drawUnusedBalance=query.uniqueResultOptional();
    
    0 讨论(0)
  • 2020-12-08 04:37
    String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
    DrawUnusedBalance drawUnusedBalance = em.unwrap(Session.class)
        .createQuery(hql, DrawUnusedBalance.class)
        .setParameter("today",new LocalDate())
        .uniqueResultOptional()
        .orElseThrow(NotFoundException::new);
    
    0 讨论(0)
  • 2020-12-08 04:44

    Yes. You need to use the try/catch block, but no need to catch the Exception. As per the API it will throw NoResultException if there is no result, and its up to you how you want to handle it.

    DrawUnusedBalance drawUnusedBalance = null;
    try{
    drawUnusedBalance = (DrawUnusedBalance)query.getSingleResult()
    catch (NoResultException nre){
    //Ignore this because as per your logic this is ok!
    }
    
    if(drawUnusedBalance == null){
     //Do your logic..
    }
    
    0 讨论(0)
  • 2020-12-08 04:45

    When you don't know whether there are any results, use getResultList().

    List<User> foundUsers = (List<User>) query.getResultList();
            if (foundUsers == null || foundUsers.isEmpty()) {
                return false;
            }
    User foundUser = foundUsers.get(0);
    
    0 讨论(0)
提交回复
热议问题