java - 如果数据存在或如果数据不存在如何检索单行 - hibernate

标签 java hibernate select

这是我在 java 中的实现,如果数据存在则检索单行,如果不存在数据则检索 null 或空。

public SalesForecast isSalesForecastUser(String mobile) throws LookupException {
        SalesForecast salesForecast = null;
        Session session = null;
        try {
            session = hibernateTemplate.getSessionFactory().openSession();
            salesForecast = (SalesForecast) session.createQuery(" from SalesForecast salesforcast where salesforcast.ppUserMobile ='" + mobile + "' ").list().get(0);
        } catch (NullPointerException n) {
            n.printStackTrace();
        } catch (IndexOutOfBoundsException n) {
            n.printStackTrace();
        } finally {
            session.close();
        }

        return salesForecast;
    }

如果有单行或多行,这工作正常,但当没有匹配的行时抛出此异常:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

最佳答案

你可以这样试试

    Query query = session.createQuery(" from SalesForecast salesforcast where
                                  salesforcast.ppUserMobile ='" + mobile + "' ");
    List results = query.list();
    if(results!=null){
        return results.get(0);
    } else{
        return null;
    }

在你当前的代码中

 salesForecast = (SalesForecast) session.createQuery(" from SalesForecast 
 salesforcast where salesforcast.ppUserMobile ='" + mobile + "' ").list() 
 // list will null if no result there, So you will get NullPoiterException

关于java - 如果数据存在或如果数据不存在如何检索单行 - hibernate ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21374760/

相关文章:

hibernate - 什么时候保存实例?

mysql - Spring JPA 选择集合中的元素

mysql - 如何使用 mySQL 选择一列具有最大值并按另一列分组的结果?

c# - 如何将 CLOB 字段读入 C# 变量?

java - 生成 Excel 标题时更改特定文本的颜色

java - 如何使用 split 方法查找 .txt 的 double 的两个特定列的平均值

Java:如何查找给定时区月底的时间戳

java - Artifactory 中的 GAVC 搜索不考虑分类器

java - 使用不同的外键 id 复制同一类的对象

MySQL 选择里面的选择里面的选择