简体   繁体   中英

Resolving Java.lang.ClassCastException

I am quite new in hibernate. I am really stuck in Java.lang.ClassCastException problem. Cant resolve this problem of my below code for whole day. Can any on help me please?

@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;
    }

I have read this but can'tresolve this problem.

I don't understand how the result of that queries can be casted to Product instances, specifically including a count() in the select.

I would change the below part of the query

select productName, count(productName) as totalSold from Product

to this

SELECT * FROM Product

(Maybe replace * with the actual column names )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM