解决 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;

    }

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


拉莫斯之舞
浏览 242回答 2
2回答

慕村225694

I suppose you are getting error at this line:List<Product> productList = session.createQuery(" select productName, count(productName) as totalSold&nbsp; 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))&nbsp; from Product where sell='1' group by productName order by count(productName) desc").setCacheable(true).list();

白猪掌柜的

我不明白如何将查询的结果转换为 Product 实例,特别是在选择中包含 count() 。我会更改查询的以下部分select&nbsp;productName,&nbsp;count(productName)&nbsp;as&nbsp;totalSold&nbsp;from&nbsp;Product对此SELECT&nbsp;*&nbsp;FROM&nbsp;Product(也许用实际的列名替换 * )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java