java - 解决 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;
}
我已阅读此内容,但无法解决此问题。
解决方案
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();
推荐阅读
- slack - Slack 机器人如何找到自己的 id?
- linker - 网站注册号以电话号码链接的形式出现,有没有办法逃脱?
- python - Selenium 的 XPath 问题
- python - 除了在 OpenCV (Python) 中作为坐标提供的多边形之外的遮光图像
- sql - 访问 - 选择从一对多表中返回“一”的查询
- reactjs - 从 react-redux、Parent vs Child 组件中使用 connect() 的首选方式是什么?
- swift - SpriteKit - 如何修复节点动画中的失真?
- xml - 如何使用带有约束的 DOM 针对 XSD 验证 XML?
- spring-data-mongodb - mongodb 的 querydsl 是否支持 $text (full text) 搜索?(使用带有spring数据mongodb的querydsl)
- r - R中自动一张一张选择图像文件的功能