编程语言
首页 > 编程语言> > Hibernate with ProjectionList错误:无法强制转换为[Ljava.lang.Object;

Hibernate with ProjectionList错误:无法强制转换为[Ljava.lang.Object;

作者:互联网

我的对象的returnig列表有问题.我正在使用@EmbeddedId的实体类,你可以在下面的代码中看到,其中有两行文字相似:id.*.

Criteria cr = createCriteria(true);
cr.add(Restrictions.eq("id.qwerty", "QWERTY"));

ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("id.qwerty"));
projectionList.add(Projections.property("text"));
projectionList.add(Projections.property("id.property"));
cr.setProjection(projectionList);
cr.setResultTransformer(Transformers.aliasToBean(My.class));

List<My> myList = (List<My>) cr.list();

return myList;

在行列表< My> messagesList =(List< My>)cr.list();发生以下错误.

java.lang.ClassCastException: my.package.dao.domain.My cannot be cast to [Ljava.lang.Object;
at org.hibernate.cache.StandardQueryCache.put(StandardQueryCache.java:104)
at org.hibernate.loader.Loader.putResultInQueryCache(Loader.java:2274)
at org.hibernate.loader.Loader.listUsingQueryCache(Loader.java:2206)
at org.hibernate.loader.Loader.list(Loader.java:2164)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1706)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)

在这种情况下,如何定义Criteria或ProjectionList?

编辑

@javax.persistence.Entity
@Table(name = "my_table")
public class My extends MyEntity<MyPK> {

   @EmbeddedId
   private MyPK id;

   @Column(name = "text", nullable = false)
   protected String text;

   @ManyToOne
   @JoinColumn(name = "property", nullable = false, insertable = false, updatable = false)
   protected Option option;

   @Override
   public MyPK getId() {
       return id;
   }

   @Override
   public void setId(MyPK id) {
       this.id = id;
   }

   //getters and setter
   //equlas and hashCode
}

和MyPK课程:

@Embeddable
public class MyPK implements Serializable {

   @Column(name = "qwerty")
   protected String qwerty;

   @Column(name = "property")
   protected String property;

   //constructors, getters and setters
}

解决方法:

如果在Criteria上使用setProjection(),则list()方法将返回List< Object>的类型.或列表< Object []>,具体取决于您添加到投影列表的属性数量.

这意味着您必须自己创建My实例.

    List<My> myList = new ArrayList<My>();
    for (Object[] row : cr.list()) {
         My m = new My();
         m.setQwerty((String) row[0]);
         // set the rest of the properties
         myList.add(m);
    }

我相信您看到的ClassCastException是因为list()方法返回了Object实例,但是您已通过设置ResultTransformer明确询问了My实例

Similar question here, answered by JBNizet

标签:criteria-api,projection,java,hibernate
来源: https://codeday.me/bug/20190826/1726188.html