使用带有 ResultTransformer 和投影的 Hibernate DetachedCriteria 未检索实体列表

Entities list not retrieved with Hibernate DetachedCriteria with ResultTransformer and projection

当尝试使用 spring REST 和休眠检索实体列表时,我遇到了转换数据和投影策略的问题,即使我的列表是从 DAO 层检索的,但不是从我的方法服务返回的我休息 API。 我收到错误 500。

这是我的控制器方法:

@PostMapping(value = "/Users")
public SearchResult<User> search(@RequestBody SearchCriteria searchCriteria) {
    try {
        return userService.searchPaginatedUsers(searchCriteria);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

对于服务实施:

  @Override
  public SearchResult<User> searchPaginatedUsers(SearchCriteria search) {
    List<User> users;
    SearchResult<User> result = new SearchResult<>();
    try {
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);

        String login = search.getAttributeByCode("login");
        String firstName = search.getAttributeByCode("firstName");
        String lastName = search.getAttributeByCode("lastName");

        if (StringUtils.isNotBlank(login))
            criteria.add(Restrictions.eq("login", login));
        if (StringUtils.isNotBlank(firstName))
            criteria.add(Restrictions.eq("first_name", firstName));
        if (StringUtils.isNotBlank(lastName))
            criteria.add(Restrictions.eq("last_name", lastName));

        result.setTotalRecords(userDAOService.getCountFromCriteria(criteria));

        if (search.getPageNumber() >= 0 && search.getPageSize() > 0) {
            criteria.setProjection(null);
            criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            users = userDalService.searchByCriteriaPaginated(criteria, search.getPageNumber(),
                    search.getPageSize());
            result.setResults(users);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

正如我在调试和发送 HTTP 请求时提到的,我的用户列表是从 DOA 层返回的。

欢迎任何想法。 谢谢

通过像这样添加投影列表来解决:

            ProjectionList projList = Projections.projectionList();
            projList.add(Projections.property("login"), "login");
            projList.add(Projections.property("first_name"), "first_name");
            projList.add(Projections.property("last_name"), "last_name");


            criteria.setProjection(Projections.distinct(projList));
            criteria.setResultTransformer(new 
             AliasToBeanResultTransformer(User.class));