Unable to cast Object to Pojo class [duplicate] - java

I use JPA 1.0:
Query query;
query = em.createNamedQuery("getThresholdParameters");
query.setParameter(1, Integer.parseInt(circleId));
List<Object[]> resultList = new ArrayList();
resultList = query.getResultList();
Here I get result as List<Object[]>, thus I have to type convert all the parameters of the row to their respective types which is cumbersome.
In JPA 2.0 there is TypedQuery which return an entity object of type one specifies.
But as I am using JPA 1 I can't use it.
How to get result as Entity object of type I want??
EDIT:
QUERY
#Entity
#Table(name="GMA_THRESHOLD_PARAMETERS")
#NamedQuery(
name = "getThresholdParameters",
query = "select gmaTh.minNumberOc, gmaTh.minDurationOc, gmaTh.maxNumberIc, gmaTh.maxDurationIc, gmaTh.maxNumberCellId,"
+ "gmaTh.distinctBnumberRatio, gmaTh.minPercentDistinctBnumber from GmaThresholdParameter gmaTh "
+ "where gmaTh.id.circleId=?1 AND gmaTh.id.tspId=?2 AND gmaTh.id.flag=?3 "
)

Your query selects many fields. Such a query always returns a list of Object arrays. If you want a list containing instances of your GmaThresholdParameter entity, then the query should be
select gmaTh from GmaThresholdParameter gmaTh
where gmaTh.id.circleId=?1 AND gmaTh.id.tspId=?2 AND gmaTh.id.flag=?3
The code to get the list of entities would then be
List<GmaThresholdParameter> resultList = query.getResultList();
You'll get a type safety warning from the compiler, that you can ignore.

I can't respond to this as a comment so I'll just go ahead and make it an answer.
List<Object[]> resultList = new ArrayList(); // CREATE an empty ArrayList object
resultList = query.getResultList(); // getResultList ALSO returns its own ArrayList object
And since you assign the list that getResultList() returns to the same variable as you used for your own empty ArrayList, your application loses any connection to your own empty ArrayList and Java will collect it as garbage. Essentially you created it for absolutely no purpose.
what JB Nizet posted is enough.
List<GmaThresholdParameter> resultList = query.getResultList();

I have done something similar since I was using JPA 1 at that time:
final Collection<YourType> typedResult = new ArrayList<YourType>
for(final Object result : query.getResultList())
{
typedResult.add((YourType) result);
}
return typedResult;

List<GmaThresholdParamerter> result= query.getResultList();
for( GmaThresholdParamerter res : result)
{
System.out.println("" +res.getMinNumberOc());
System.out.println("" +res.getMinDurationOc());
}

Related

How to pass list in hql query where list is a value of a map

I have a leaveList containing 4 leave names.This leaveList is passed as map value.I want to get leave details from CompanyLeave Table by passing leaveList in hql query.Let be considered,my Company Leave Table contains 6 leave details.leaveList has 3 leave names.I want to get details of these 3 leaves from CompanyLeave Table.
Code for Hql query here leaveNameList is a list as well as map
public List<CompanyLeaveType> getByValidLeave(Map<String, Object> params) {
Query query = sessionfactory.getCurrentSession().createQuery("from CompanyLeaveType WHERE companyCode = :companyCode and leaveName IN (:leaveNames)");
query.setParameter("companyCode", params.get("companyCode"));
query.setParameter("leaveNames", params.get("leaveNameList"));
List<CompanyLeaveType> validLeaveDetails = query.list();
return validLeaveDetails;
}
N.B: I have got java.util.ArrayList cannot be cast to java.lang.String error.How can I pass list in hql query?
Use query.setParameterList(), Check the documentation here.
Query query = sessionfactory.getCurrentSession().createQuery("from CompanyLeaveType WHERE companyCode = :companyCode and leaveName IN (:leaveNames)");
query.setParameter("leaveNames", params.get("leaveNameList"));
Here you are trying to add a list object to the Hql query.
Here in this case the generated query by hibernate looks like this(actually its not happened and is just to make you to understand whats going on here)
1) Select *from companyLeveType_Table where companyCode=someX and leaveName in(ListObject)
But here the leaveName is of type java.lang.String and hence hibernte frameworks expects the values should be the string only. see the sample code (Hibernte expects this)
2) Select *from companyLeveType_Table where companyCode=someX and leaveName in("A","B","C");
from first query its obvious that hibernate framework tries to convert the java.util.ArrayList to java.lang.String and hence exception throws.
Solution 1)
public List<CompanyLeaveType> getByValidLeave(Map<String, Object> params) {
Query query = sessionfactory.getCurrentSession().createQuery("from CompanyLeaveType WHERE companyCode = :companyCode and leaveName IN (:leaveNames)");
query.setParameter("companyCode", params.get("companyCode"));
query.setParameterList("leaveNames", params.get("leaveNameList")); // changes here only remaining is same
List<CompanyLeaveType> validLeaveDetails = query.list();
return validLeaveDetails;
}
Solution 2:
Use Criteria api.
public List<CompanyLeaveType> getByValidLeave(Map<String, Object> params) {
Criteria criteria=session.createCriteria(CompanyLeaveType.class);
criteria.addCriteria(Restrictions.eq("companyCode",params.get("companyCode")))
.addCriteria(Restrictions.in("leaveName",params.get("leaveNameList")));
List<CompanyLeaveType> validLeaveDetails =criteria.list();
return validLeaveDetails;
}
I hope this helps you

Difference bettween transformTuple and For loop on query Result - Hibernate

I have an HQL as select p,c from Person p,ContactCard c where c.fk_pid=p.id I executed this query as HQL using this code:
List<Person> personsWithContactCard = new ArrayList<Person>();
List<object[]> quryResult = new ArrayList<object[]>();
String qry = "select p,c from Person p,ContactCard c where c.fk_pid=p.id";
quryResult = session.createQuery(qry).list();
for(object[] obj : quryResult )
{
Person person = new Person();
person = (Person)obj[0];
person.setContactCard = (ContactCard )obj[1];
personsWithContactCard.add(person);
person=null;
}
By taking query result in list of object array and looping on query result I fill persons list.
But after reading about ResultTransformer Interface I come to know that with this interface I can transform queryResult in to desired list so I changed my code To :
String qry = "select p,c from Person p,ContactCard c where c.fk_pid=p.id";
personsWithContactCard = session.createQuery(qry).setResultTransformer(new ResultTransformer() {
#Override
public Object transformTuple(Object[] tuple, String[] aliases)
{
Person person = new Person();
person = (Person)obj[0];
person.setContactCard = (ContactCard )obj[1];
return person ;
}
#Override
public List transformList(List collection)
{
return collection;
}
}).list();
This code gives me persons list with for looping.
So my question is : What is the difference between transformTuple and For loop?
Does the both are same in performance and processing sense?
Which will be more good as per performance?
And what is the use of transformList()?
Update :
After understanding use of ResultTransformer as explained in answer given by #bellabax I did one small change in code as follows:
personsWithContactCard = session.createQuery(qry).setResultTransformer(new ResultTransformer() {
#Override
public Object transformTuple(Object[] tuple, String[] aliases)
{
Person person = new Person();
person = (Person)obj[0];
person.setContactCard = (ContactCard )obj[1];
return person ;
}
#Override
public List transformList(List collection)
{
return null;
}
}).list();
I changed transformList() method to return null if I execute this code I am getting null personsWithContactCard list. Why transformList() method is need to return collection when I am not using it? And when I supposed to use transformList() and transformTuple() means how I can decide which to use?
There aren't differences in terms of result usually, but using a ResultTransformer:
is the standard Hibernate method to process tuple and future (break) changes about how HQL is processed and tuple returned will be masked by a ResultTransformer without code changes
give you the possibilities to decorate or delegate (for example)
so the choice is the ResultTransformer.
About ResultTransformer.transformList():
Here we have an opportunity to perform transformation on the query
result as a whole
instead in transformTuple you can manipulate only one row of returned set.
EDIT:
As quoted above the javadoc of ResultTransformer.transformList() is pretty clear: this function allow to modify the whole list to remove duplicate, apply type conversion and so on and the result of ResultTransformer.transformList() is forwarded to Query.list() method so, return null from transformList whill return null from list().
This is how Query and ResultTransformer are tied.

Get values from list object

I have code like this...
Query query = em.createQuery("select CM.salesAreaId, SM.salesAreaDesc, count(CM.salesAreaId), sum(CM.openBal), " +
"sum(CM.netSales) from CustomerMaster CM, SalesAreaMaster SM where CM.salesAreaId=SM.salesAreaCode and CM.companyId=SM.companyId" +
" and CM.companyId=:companyId group by CM.salesAreaId, SM.salesAreaDesc");
query.setParameter("companyId", companyId);
List list = query.getResultList();
From above code how can i get the list values?(list.get() values prints objects)
Try this
Query query = em.createQuery("select CM.salesAreaId, SM.salesAreaDesc, count(CM.salesAreaId), sum(CM.openBal), " +
"sum(CM.netSales) from CustomerMaster CM, SalesAreaMaster SM where CM.salesAreaId=SM.salesAreaCode and CM.companyId=SM.companyId" +
" and CM.companyId=:companyId group by CM.salesAreaId, SM.salesAreaDesc");
query.setParameter("companyId", companyId);
List list = query.getResultList();
for(Object o : list) {
Object[] obj = (Object[])o;
}
And the value of CM.salesAreaId should be in obj[0]
You could use a for loop to iterate through, providing the index each time.
for (int i = 0; i < list.size(); i++)
{
Object x = list.get(i);
...
}
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#get(int)
as JPA is an ORM spec, query result will necessary be a set of Objects. There is a workaround with hibernate if you're using this last as JPA implementation (see How to fetch hibernate query result as associative array of list or hashmap) but your code will be heavily coupled to hibernate then.
If you want to retrieve result as a resultSet (set of primitive values) you should use jdbc directly.
If your problematic is just to print the result in an human readable way you should override toString() method for all your JPA entities.

How to run an aggregate function like SUM on two columns in JPA and display their results?

I am new to JPA. So my question should be so simple to some.
Below is the Simple Query in SQL which i would like to convert to JPA. I already have an entity class called TimeEnt.
SELECT
SUM(TimeEntryActualHours) as UnBilledHrs,
SUM (TimeEntryAmount) as UnbilledAmount
FROM TimeEnt WHERE MatterID = 200
The JPA Query Language does support aggregates functions in the SELECT clause like AVG, COUNT, MAX, MIN, SUM and does support multiple select_expressions in the SELECT clause, in which case the result is a List of Object array (Object[]). From the JPA specification:
4.8.1 Result Type of the SELECT Clause
...
The result type of the SELECT
clause is defined by the the result
types of the select_expressions
contained in it. When multiple
select_expressions are used in the
SELECT clause, the result of the query
is of type Object[], and the
elements in this result correspond in
order to the order of their
specification in the SELECT clause
and in type to the result types of
each of the select_expressions.
In other words, the kind of query you mentioned in a comment (and since you didn't provide your entity, I'll base my answer on your example) is supported, no problem. Here is a code sample:
String qlString = "SELECT AVG(x.price), SUM(x.stocks) FROM Magazine x WHERE ...";
Query q = em.createQuery(qlString);
Object[] results = (Object[]) q.getSingleResult();
for (Object object : results) {
System.out.println(object);
}
References
JPA 1.0 Specification
4.8.1 Result Type of the SELECT Clause
4.8.4 Aggregate Functions in the SELECT Clause
Lets think we have entity called Product:
final Query sumQuery = entityManager
.createQuery("SELECT SUM(p.price), SUM(p.sale) FROM Product p WHERE p.item=:ITEM AND ....");
sumQuery.setParameter("ITEM","t1");
final Object result= sumQuery.getSingleResult(); // Return an array Object with 2 elements, 1st is sum(price) and 2nd is sum(sale).
//If you have multiple rows;
final Query sumQuery = entityManager
.createQuery("SELECT SUM(p.price), SUM(p.sale) FROM Product p WHERE p.item in (" + itemlist
+ ") AND ....");
// Return a list of arrays, where each array correspond to 1 item (row) in resultset.
final List<IEniqDBEntity> sumEntityList = sumQuery.getResultList();
Take a look at the EJB Query Language specification.
The idiom is very similiar to standard SQL
EntityManager em = ...
Query q = em.createQuery ("SELECT AVG(x.price) FROM Magazine x");
Number result = (Number) q.getSingleResult ();
Regards,

Hibernate: how do I retrieve my entities from a ScrollableResults?

I do a query that returns a list of entities. How can I retrieve the entities from a ScrollableResults:
Session s = ....;
Query q = s.createQuery("....") # returns 100000s rows
ScrollableResults sr = q.scroll();
sr.scroll(45999); # just a number
Employee employee = ???
How do I get an employee in the last line of code
try the get(0) method, or get()[0]
Here's a link to API: ScrollableResults
get() returns the entire current row, get(index) returns object at index position without initializing the rest of them. There are also a bunch of convenience getXXX() methods that cast result to given type.
I do a query that returns a list of entities. How can I retrieve the entities from a ScrollableResults... How do I get an employee.
Just to improve the other answers, the ScrollableResults does the entity conversion for you although this isn't immediately clear from the Javadocs.
As #Bozho says, calling sr.get() will return the entity at the current location, but wrapped in an array. In looking at the code for ScrollableResultsImpl the current row's result is set with:
if ( result != null && result.getClass().isArray() ) {
currentRow = (Object[]) result;
} else {
currentRow = new Object[] { result };
}
So ScrollableResults.get() always returns an array of results and if your entity is not an array, it will be at get()[0].
So, with your code you would do something like:
while (sr.next()) {
// get the entity which is the first element in an Object[]
Employee employee = sr.get()[0];
...
}
To retrieve entities the simplest way would be to cast the object to whichever object you want:
E.g:
ScrollableResults sr = q.scroll();
while (sr.next()) {
CustomObject object = (CustomObject) sr.get()[0]; // Now CustomObject will have all the properties mapped
}
This works perfect for all the scenarios.

Categories

Resources