解决Java.lang.ClassCastException

时间:2018-07-29 16:21:05

标签: java hibernate

我刚进入休眠状态。我真的陷入了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;
    }

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

2 个答案:

答案 0 :(得分:1)

我不知道该查询的结果如何转换为Product实例,特别是在select中包括count()。

我将更改查询的以下部分

select productName, count(productName) as totalSold from Product

对此

SELECT * FROM Product

(也许用实际的列名替换*)

答案 1 :(得分:1)

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();