0

I am quite new in hibernate. I am really stuck in Java.lang.ClassCastExceptionproblem. 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.

Aritra Paul
  • 834
  • 1
  • 8
  • 14

2 Answers2

1

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 )

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
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();
Ramandeep Kaur
  • 111
  • 1
  • 9