我想获取具有不同批处理代码和 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();
最佳答案
您似乎在条件中设置了多个预测。最后一个覆盖前面的一个。为避免这种情况,您可以使用 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();
关于java - 使用 hibernate 条件获取具有不同的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38890917/