Hibernate DetachedCriteria multiple results in java

拜拜、爱过 提交于 2019-12-06 15:38:36

First of all, your SQL looks incorrect. The reason it is returning multiple rows is because you're joining against the USER_LOGIN_STATUS table which may have multiple rows per USER_PROFILE. Because you are not selecting any fields from the USER_LOGIN_STATUS table, you cannot see why there are multiple rows. Why are you joining on this table in the first place?

Secondly, the detached criteria you are performing is not equivalent to the SQL you have provided since you are doing a sub-query which you are not in the SQL.

You don't need this sub-select and since I don't understand why you are doing the join I will assume some points to give you the following example:

DetachedCriteria dc = getDetachedCriteria();
dc.createAlias("userLoginStatus", "uls");
dc.add(Projections.property("firstName")); 
dc.add(Projections.property("lastName"));
dc.add(Projections.property("userType")); 
dc.addOrder(Order.asc("firstName")); 
return getAll(dc, pageSetting);

This is now roughly equivalent but I am assuming:

  • You have the correct mappings for your relationship between UserField and UserLoginStatus.
  • That getDetachedCriteria() is effectively returning DetachedCriteria.forClass(UserField.class).

You can also now refer to a field in UserLoginStatus as so:

dc.add(Projections.property("uls.my_user_login_field"));

And as well, if you get your query sorted out and you still return multiple entities, then dinukadev's answer will then come into play with:

dc.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

I suspect the reason this isn't working for you is because of your sub-select.

Sorry I cannot help you more.

Please try to set the result transformer on your root detached criteria as follows. This will eliminate duplicates.

dc.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!