首页 > 解决方案 > 解决 Java.lang.ClassCastException

问题描述

我对休眠很陌生。我真的陷入了困境Java.lang.ClassCastException。一整天都无法解决我下面代码的这个问题。任何人都可以帮助我吗?

@Override
public ObservableList<Product> getSold() {
    ObservableList<Product> list = FXCollections.observableArrayList();
    Transaction tx=null;

    session = Hibutil.getSessionFactory().getCurrentSession();
    try {
        tx= session.beginTransaction();
        List<Product> productList = session.createQuery(" select productName, count(productName) as totalSold  from Product where sell='1' group by productName Order by totalSold desc").setCacheable(true).list();
        tx.commit();
        productList.stream().forEach(list::add);// getting error here

        System.out.println(list.get(0));
        return list;
    } catch(HibernateException e) {
        if(tx!=null)tx.rollback();
        return null;
    }

我已阅读内容,但无法解决此问题。

标签: javahibernate

解决方案


I suppose you are getting error at this line:

List<Product> productList = session.createQuery(" select productName, count(productName) as totalSold  from Product where sell='1' group by productName Order by totalSold desc").setCacheable(true).list();

You need to write DTO for this.

class ProductDto {

private ProductName;
int productCount;

//getters and setters and constructors
}

you can accordingly modify the query as:

List<ProductDto> productDtoList = session.createQuery(" select new ProductDto (productName, count(productName))  from Product where sell='1' group by productName order by count(productName) desc").setCacheable(true).list();

推荐阅读