ClassCastException even after type casting - classcastexception

I got a problem with iterating List which got prepared from HQL.
I am querying DB on a single table mapped to very simple class.
After iterating the same list and type casting to same class during iteration I am getting ClassCastException.
Code :
import HectorRequest;
import EDIMigrateData;
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.getCurrentSession();
Transaction tx = session.beginTransaction();
Query qry = session.createQuery("select hr from HectorRequest hr");
List result = qry.list();
for (Iterator it = result.iterator(); it.hasNext();) {
Object o = it.next();
if(o instanceof HectorRequest){
HectorRequest h = (HectorRequest) o;
System.out.println("ID: " + h.getId());
}
}
I wonder here If I am typecasting to the same class it is giving ClassCastException.
if(o instanceof HectorRequest) {
HectorRequest h = (HectorRequest) o;
System.out.println("ID: " + h.getId());
}
The control is not coming into the above if statement.
If I remove the above IF condition it is throwing
java.lang.ClassCastException: HectorRequest
Below is my hibernate mapping xml for HectorRequest class.
Below is my Hibernate.cfg.xml
?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property><property name="hibernate.connection.url">jdbc:oracle:thin:#//apludc01clu20-scan-oravip.dci.bt.com:61901/C2BM2_ANY</property><property name="hibernate.connection.username">s3</property><property name="hibernate.connection.password">**</property><property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property><property name="hibernate.default_schema">s3</property><property name="show_sql">true</property><property name="hibernate.current_session_context_class">thread</property><mapping resource="resources/config/hector_request.hbm.xml"></mapping></session-factory></hibernate-configuration>
Below is the output:
Hibernate: select hectorrequ0_.ID as ID0_, hectorrequ0_.ROUTER_TEL as ROUTER2_0_, hectorrequ0_.FLAGVALUE as FLAGVALUE0_, hectorrequ0_.FLAGPOS as FLAGPOS0_, hectorrequ0_.ACCOUNTNO as ACCOUNTNO0_, hectorrequ0_.CUSTOMERIDENTITY as CUSTOMER6_0_, hectorrequ0_.CRMSOURCE as CRMSOURCE0_, hectorrequ0_.DATASOURCE as DATASOURCE0_ from s3.hector_request hectorrequ0_
java.lang.ClassCastException: HectorRequest
at NotifyMain1.main(NotifyMain1.java:37)
Can someone help what is missing and wrong here.

It is because of the data returned by the query "select hr from HectorRequest hr" is not "HectorRequest". It probably is a database data type (string, number, date, time, etc). So you have to build your "HectorRequest" object using the data returned by the query and not directly assign to it with a cast.

Related

How to convert data from query with JPA Repository

I have a query that seems to work fine.
public interface GameRepository extends JpaRepository<Game,Integer> {
#Query(value="SELECT Cast(bifnb as varchar) bifnb , count(*) FROM (SELECT count(fk_game) as nb FROM public.game INNER JOIN score s on game.id_game = s.fk_game WHERE fk_board_game = 2014 GROUP BY fk_game) as bifnb group by bifnb", nativeQuery = true)
List<StatisticDto> nbplayer();
}
But when I try to use it with JPA and type StatisticDTO , I get the following error:
context with path [/api] threw exception [Request processing failed; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [****.statistics.payload.StatisticDto]] with root cause
So I tried with the same query and : List<Object> nbplayer();
It works but I don't know how to work with a List I prefer to use a StatisticDto.
Assuming StatisticDTO looks like this:
public class StatisticDTO {
private String key;
private Integer value;
// ... getter/setter
}
This query should work:
#Query(value="SELECT Cast(bifnb as varchar) as \"key\" , count(*) as \"value\" FROM (SELECT count(fk_game) as nb FROM public.game INNER JOIN score s on game.id_game = s.fk_game WHERE fk_board_game = 2014 GROUP BY fk_game) as bifnb group by bifnb", nativeQuery = true)
List<StatisticDto> nbplayer();
See this article about transforming results to DTO for more information.
I've quoted the aliases because I think key and value are special keywords.

.NET Core - EntityFrameworkCore - Unable to cast object of type 'Query.Internal.EntityQueryable` to type 'DbSet`

I try to implement a search with entity when a search field is provided
but I get a weird casting error I just dont understand
Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[SomeApp.Models.Partner]' to type 'Microsoft.EntityFrameworkCore.DbSet`1[SomeApp.Models.Partner]'.
here is the code of my controller entry point
I tried forcing the cast, but apparently there is something wrong with my code
[HttpPost]
public async Task<ActionResult<PartnersFetch>> GetPartners(PartnersSearch partnersSearch)
{
DbSet<Partner> data = _context.Partners;
if (partnersSearch.SearchById != null)
{
// the following line causes problems :
data = (DbSet <Partner>) data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
thanks for helping me on this
I forgot to use AsQueryable
var data = _context.Partners.AsQueryable();
if (partnersSearch.SearchById != null)
{
data = data.Where( p => p.Id == partnersSearch.SearchById.GetValueOrDefault());
}
data.Where(...) will return an IQueryable which you can materialize as follows
List<Partner> myResult = data.Where(...).ToList();
The DbSet<Partner> is only the set on which you can query data. Your goal very likely is to get the partners out of it, right?

Ignite SqlQuery for complex java objects

In my cache I have a complex java object as below -
class Person{
private Department d;
....
}
class Department {
private Department code;
....
}
I am using below SQLQuery to read it -
SqlQuery<Short, BinaryObject> query = new SqlQuery<>(Person.class, "d.code = ?");
String args="101"; // department code
QueryCursor<Cache.Entry<Short, BinaryObject>> resultSet = personCache.query(query.setArgs(args))
I am getting below error -
Caused by: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to parse query: SELECT "PERSON_CACHE"."PERSONENTITY"._KEY, "TPERSON_CACHE"."PERSONENTITY"._VAL FROM "PERSON_CACHE"."PERSONENTITY" WHERE id.code = ?
Am I doing anything wrong here ?
You can access nested fields, but only if they were configured with QuerySqlField annotation in advance:
class Person{
private Department d;
...
}
class Department {
#QuerySqlField
private Department code;
....
}
SqlQuery<Short, BinaryObject> query = new SqlQuery<>(Person.class, "code = ?");
Destructuring is not supported by Ignite SQL and there are no solid plans to implement it.
This means you can't peek into fields that are rich objects, maps, lists, etc. You should introduce a departmentId numeric field here.
Theoretically you could also try putting #QuerySqlField annotation on Department's field code, and then access it as CODE = ?. Your mileage may vary. I for one would like to hear about the result of such experiment.
I resolved it by using predicate.
IgniteBiPredicate<Long, BinaryObject> predicate = new IgniteBiPredicate<Long, BinaryObject>() {
#Override
public boolean apply(Long e1, BinaryObject e2) {
Person p= e2.deserialize();
short s = (short) args[0];
return p.getId().getCode == s;
}
};

Unable to cast the resultant of the query into desired object in hibernate

I am not able to cast the query result to Desired Object UserTransactionInADay.
Here is my implementation
#Override
public UserTransactionInADay getTodaysActivity() {
Date date = new Date();
String modifiedDate= new SimpleDateFormat("yyyy-MM-dd").format(date);
Session session = getSession();
session.clear();
#SuppressWarnings("unchecked")
Query qry = session
.createQuery(
"Select u.infoDate, sum(u.totalActiveUsers) as totalActiveUsers, sum(u.plotsVisited) as plotsVisited, sum(u.totalDataSet) as totalDataSet, sum(u.totalAlerts) as totalAlerts, sum(u.totalCropStages) as
totalCropStages, sum(u.activitiesClosed) as activitiesClosed, sum(u.totalPlotInput) as totalPlotInput, sum(u.totalHarvest) as totalHarvest from UserTransactionInADay u where u.infoDate = ? group by u.infoDate");
qry.setString(0, modifiedDate);
List<UserTransactionInADay> userTransactionInADay = qry.list();
return userTransactionInADay.get(0);
}
Error I thrown like this
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.raghu.model.UserTransactionInADay
com.raghu.dao.CropinDaoImpl.getTodaysActivity(CropinDaoImpl.java:92)
com.raghu.service.CropinServiceImpl.getTodaysActivity(CropinServiceImpl.java:68)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
I think you need to review some of the Hibernate docs a bit. You are selecting a bunch of data and trying to cast it to an entity (I assume) collection.
What your query will return is an Object[][].
Assuming your UserTransactionInADay has the appropriate constructor, you'll want to do something like this:
"SELECT NEW UserTransactionInADay(u.infoDate, sum(u.totalActiveUsers)
AS totalActiveUsers, SUM(u.plotsVisited) AS plotsVisited,
SUM(u.totalDataSet) AS totalDataSet, SUM(u.totalAlerts) AS totalAlerts,
SUM(u.totalCropStages) AS totalCropStages, SUM(u.activitiesClosed) AS activitiesClosed,
SUM(u.totalPlotInput) AS totalPlotInput, SUM(u.totalHarvest) AS totalHarvest)
FROM UserTransactionInADay u WHERE u.infoDate = ? GROUP BY u.infoDate"
This will return UserTransactionInADay objects, again, assuming there is an appropriate constructor for that type.

Is there a way to do a "in" statment in javax.persistence.Query [duplicate]

I have the following parametrised JPA, or Hibernate, query:
SELECT entity FROM Entity entity WHERE name IN (?)
I want to pass the parameter as an ArrayList<String>, is this possible? Hibernate current tells me, that
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String
Is this possible at all?
ANSWER: Collections as parameters only work with named parameters like ":name", not with JDBC style parameters like "?".
Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:
String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
For Hibernate's, you'll need to use the setParameterList:
String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);
in HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.
String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:
Entity.java:
#Entity
#NamedQueries({
#NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
#Column(name = "attribute")
private String attribute;
}
Dao.java:
public class Dao {
public List<Entity> findByAttributes(Set<String> attributes) {
Query query = em.createNamedQuery("byAttributes");
query.setParameter(1, attributes);
List<Entity> entities = query.getResultList();
return entities;
}
}
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue