Tag Archives: java.lang.ClassCastException: Ljava.lang.Object; cannot be cast to com.entity.Advertisem

[Solved] java.lang.ClassCastException: Ljava.lang.Object; cannot be cast to com.entity.Advertisem

 I accidentally ran into such a problem today. I have never encountered it before. I searched a lot of methods on the Internet. The idea is correct, but I still need to change it according to my own procedures.

At the beginning, I wrote the hql statement to count the data of each month, but after a long trial, the program kept reminding the hql statement to be abnormal. There was no way to modify the query statement, and it was changed to the sql statement for statistics.

The error occurred from this, and it was out of control:

java.lang.ClassCastException: Ljava.lang.Object; cannot be cast to com.entity.Advertisem This exception solution is very simple, we must first understand

hibernate in createQuery and createSQLQuery difference:

The former uses hql statements to query, the latter can use SQL statements to query the
former uses hibernate-generated beans as objects to load into the list and returns, and the
latter
uses object arrays for storage. So using createSQLQuery sometimes I want to use hibernate-generated beans as objects. It is not very convenient to load the list and return,
but createSQLQuery has such a method to directly convert the object
Query query = session.createSQLQuery(sql).addEntity(XXXXXXX.class)
XXXXXXX represents the object of the Bean generated by hibernate, that is, the data table mapping Bean

 

 hql statement: Statistics on the data of each month
String hql = “select sum(sto_Sum), sum(sto_SumPrice) ,sum(sto_SaleNum) ,sum(sto_SaleNum*sto_SalePrice) from Stock WHERE PERIOD_DIFF( date_format( now(),’% Y%m’), date_format( addDate,’%Y%m’)) =1”;
Query query = session.createSQLQuery(hql).addEntity(Stock.class);//Key steps
list = query.list() ;

So the problem is that the type does not match and the conversion cannot be performed. The problem is solved like this! ! !