Reputation: 874
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.
Upvotes: 0
Views: 212
Reputation: 111
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();
Upvotes: 1
Reputation: 51831
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 )
Upvotes: 1