我有这个代码
StatesProvinces statesProvinces = new StatesProvinces();
ArrayList<StatesProvinces> allStates = new ArrayList<StatesProvinces>();
ArrayList<String> states = new ArrayList<String>();
Session session = sessionFactory.openSession();
Criteria crit = session.createCriteria(StatesProvinces.class);
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List rsList = crit.list();
for (Iterator it = rsList.iterator(); it.hasNext();) {
statesProvinces = (StatesProvinces) it.next();
allStates.add(statesProvinces);
String state = statesProvinces.getState();
states.add(state);
}
return states;
我得到的结果具有相同的状态,例如阿拉斯加8次,在那里应该只有1次我使用上面的不同,但它不起作用..我错了?
感谢
答案 0 :(得分:0)
以下代码将给出您的唯一状态列表:
Criteria criteria = getHibernateSession().createCriteria(StatesProvinces.class);
ProjectionList projectionList = Projections.projectionList()
.add(Projections.property("state"));
criteria.setProjection(Projections.distinct(projectionList));
list = criteria.list();
hibernate distict的缺点是我们只能将其用于投影,如果我们需要整个实体,我们必须向所有字段添加投影并使用setReusultTransformer,如下所示:
criteria.setResultTransformer(Transformers.aliasToBean(StatesProvinces.class));