使用休眠条件获取具有不同的 id

get id with distinct with hibernate criteria

我想获取具有不同批次代码和 ID 的行。

下面的代码现在正在获取重复的批次代码,例如:

batch1 12,
batch1 45,
batch1 63,
batch2 96,
batch2 96

@Entity
@Table(name = "key")
public class Key implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, length = 11)
    @Column(name = "batch_code", nullable = false)
    private String batchCode;

    //getter , setter
}



Criteria c = getSession().createCriteria(Key.class);

ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("batchCode"));

c.setProjection(Projections.distinct(projList));
c.setProjection(Projections.property("id"));

if (searchTerm != null && !searchTerm.isEmpty()) {
    c.add(Restrictions.like("keyCode", searchTerm.toUpperCase() + "%"));
}

c.setFirstResult(currPosition);
c.setMaxResults(pageSize);

List<Key> result = c. list();

我发现 this question 与您的相似,但尚未解决。

在评论中,OP 表示这个小改动可能会解决您的问题:

 ProjectionList projList = Projections.projectionList();
 projList.add(Projections.property("batchCode"));
 projList.add(Projections.property("id"));     
 c.setProjection(Projections.distinct(projList));

另请注意,在上面的链接问题中,没有实体 class 设置为 Criteria

 Criteria c = this.createCriteria();

所以list方法的执行返回了一个List<Object[]>。我不知道您是否会在尝试获取 Key 个对象

时遇到 ClassCastException

您似乎在条件中设置了多个预测。最后一个覆盖前面的一个。为避免这种情况,您可以使用 ProjectionList 添加多个投影,如下所示

    Criteria c = getSession().createCriteria(Key.class);
    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.distinct(Projections.property("batchCode")));
    projList.add(Projections.property("id"));
    c.setProjection(projList);
      if (searchTerm != null && !searchTerm.isEmpty()) {
          c.add(Restrictions.like("keyCode", searchTerm.toUpperCase() + "%"));
      }
    c.setFirstResult(currPosition);
    c.setMaxResults(pageSize);
    List<Key> result = c. list(); 

我猜你正在尝试的场景是无效的。批号和 id 字段不是唯一组合,也不是复合键。现在在下方 table 如果您只需要唯一的批处理代码,您可以创建 SQL 查询,例如“Select distinct batchcode from ”,但我从对话中了解到,您需要一个完整的记录批处理代码和不同批次代码的 id。在这种情况下,系统如何确定哪个记录需要 return 对于任何重复的批次代码,即 abc。这里系统没有任何提示是 return (1, abc) or (2, abc) or (4, abc)。 如果这是用例,那么您需要验证您实际想要实现的业务场景。

编号 |批号

1 |美国广播公司

2 |美国广播公司

3 | xyz

4 |美国广播公司

5 |荷航