HIbernate:选择多个不同的列导致错误

时间:2018-01-18 07:40:56

标签: java sql spring hibernate hibernate-criteria

我正在尝试执行查询

Hibernate: select distinct this_.platform as y0_, this_.device as y1_, this_.date as y2_ from my_lab this_ where this_.brand=? and this_.network=?

使用代码:

    Criteria crit = entityManager.unwrap(Session.class).createCriteria(Lab.class);

    ProjectionList projList = Projections.projectionList();

    if (platform == null) {
        projList.add(Projections.property("platform"));
    } else {

        crit.add(Restrictions.eq("platform", platform));
    }

    if (device == null) {
        projList.add(Projections.property("device"));
    } else {

        crit.add(Restrictions.eq("device", device));
    }

    if (date == null) {
        projList.add(Projections.property("date"));
    } else {
        crit.add(Restrictions.eq("date", dateOfVideo));
    }

    if (brand == null) {
        projList.add(Projections.property("brand"));
    } else {
        crit.add(Restrictions.eq("brand", brand));
    }


    if (network == null) {
        projList.add(Projections.property("network"));
    } else {
        crit.add(Restrictions.eq("network", network));
    }

    crit.setProjection(Projections.distinct(projList));

    List<String> list = crit.list();
    return list;

但是当我打电话给这项服务时,它会给我以下错误:

 "Could not write content: [Ljava.lang.Object; cannot be cast to java.lang.String; nested exception is com.fasterxml.jackson.databind.JsonMappingException: [Ljava.lang.Object; cannot be cast to java.lang.String",

无法理解原因。在get请求中也提到了produces={MediaType.APPLICATION_JSON_VALUE}

1 个答案:

答案 0 :(得分:0)

我认为问题就在于行

List<String> list = crit.list();

实际上,如果有多个投影,您应该期待List<Object>并访问像这样的值

List<Object> rows = crit.list();
for(Object r: rows){
  Object[] row = (Object[]) r;
}