【问题标题】:HQL Select QueryHQL 选择查询
【发布时间】:2016-09-09 08:46:36
【问题描述】:

如何根据唯一列选择行。 在我的表中,Id 是自动生成的。我正在使用电话号码来选择我的表架构中唯一的行。

例如:

 Id    Phone      Name
 1     2209897    abc
 2     5436567    def

这里,Id 是主键。 电话是独一无二的。

我正在使用手机登录。 我不希望生成一个列表,而是生成单行作为输出。

 @Repository
 public class CustomerDetailsDAOImpl implements CustomerDetailsDAO {

@Autowired
SessionFactory sessionFactory;

@Override
@Transactional
public List<CustomerDetails> getCustomer(String customerPhone) {
    Session session = sessionFactory.openSession();

    Query q = session.createQuery("from CustomerDetails where customerPhone =:p");
    q.setParameter("p", customerPhone);

    List<CustomerDetails> customer = q.getResultList();
    session.close();
    return customer;

}

【问题讨论】:

  • 不要使用List,只使用CustomerDetails customer = q.getResultList();,如果:p返回超过1行那么你会得到一个ResultSizeException,但是如果数据库中的所有电话号码都是当然是独一无二的,那么您应该没有任何问题。
  • @px06 可能您打算建议使用 q.getResultList() 以外的方法。
  • @Gimby 对不起,你是对的。应该是:List&lt;CustomerDetails&gt; getList = q.getResultList(); Customer customer = getList.get(0);

标签: java hibernate hql dao


【解决方案1】:

使用 getSingleResult() 而不是使用 getListResult()。这将执行一个返回单个无类型结果的 SELECT 查询。因此,当您希望检索到具有唯一类型的单个记录时,应使用 getSingleResult()。

 @Repository
 public class CustomerDetailsDAOImpl implements CustomerDetailsDAO {

@Autowired
SessionFactory sessionFactory;

@Override
@Transactional
public List<CustomerDetails> getCustomer(String customerPhone) {
    Session session = sessionFactory.openSession();

    Query q = session.createQuery("from CustomerDetails where customerPhone =:p");
    q.setParameter("p", customerPhone);

    CustomerDetails customer = q.getSingleResult();
    session.close();
    return customer;

}

希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    不要使用q.getResultList(),而是使用q.getSingleResult(),因为电话号码在您的数据库中是唯一的,查询将返回CustomerDetails 类的单个对象。

    public CustomerDetails getCustomer(String customerPhone) {
        Session session = sessionFactory.openSession();
    
        Query q = session.createQuery("from CustomerDetails where customerPhone =:p");
        CustomerDetails customer=null;
        q.setParameter("p", customerPhone);
        try{
            customer = q.getResultList();
        }catch(NoResultException ex){
        System.out.println(ex.getMessage());
    
        }finally{
            session.close();
        }
    
        return customer;
    
    }
    

    注意:如果您的查询没有从数据库中检索到任何数据,那么getSingleResult() 将抛出NoResultException 异常。 所以你必须从你身边处理这个异常。

    您可以参考上面的例子。我为NoResultException 异常处理添加了代码。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2011-09-25
    • 1970-01-01
    • 2020-04-19
    • 2013-07-10
    相关资源
    最近更新 更多