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.

2
  • 1
    Do you mind share the stack trace of the error or at which line you are getting this error? Commented Jul 29, 2018 at 16:22
  • @AmanChhabra I am getting error ` productList.stream().forEach(list::add)`in this line Commented Jul 29, 2018 at 16:49

2 Answers 2

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 )

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.