return第一次出现查询结果springhql

return the first occurrence of a query result spring hql

我有一个 returns json 结果的端点。看起来数据库中的某些行是重复的。我只想检索第一个匹配的结果而忽略其余的。这是我在 DAO

中的 HQL
@SuppressWarnings("unchecked")
    public List <Data> getDetails(String tin) {
        return  sessionFactory.getCurrentSession().createQuery("from Data where cal_no = :cal_no")
                .setParameter("cal_no",  tin).list();
    }

这里是hql的输出格式

[{"id":15274,"cal_NO":"37"}{"id":15275,"cal_NO":"37"}]

可以看到cal_NO重复了两次,因为cal_no和37在dbd中存在了两次。我的挑战是只选择第一个出现的地方而忽略其余的。

您可以创建一个 Criteria 对象并使用 setMaxResults(1) 获得一个项目 或者 试试这段代码:

@SuppressWarnings("unchecked")
    public List <Data> getDetails(String tin) {
        List <Data> dataList = new ArrayList<>();
        List <Data> results = sessionFactory.getCurrentSession().createQuery("from Data where cal_no = :cal_no")
                .setParameter("cal_no",  tin).list();
        if(CollectionUtils.isNotEmpty(results){
            Data firstDataOccurence = results.get(0);
            dataList.add(firstDataOccurence);
            return dataList;
        }
        else{
            return ListUtils.EMPTY_LIST;
        }
    }