I'm fetching object list from session.createSQLQuery().
I didnt make any pojo classes for it because I don't want it
This object contain 2 variables , I want to fetch those variables who can I
My code
session = sessionfactory.openSession() ;
query = session.createSQLQuery("select id from A_Cleanup") ;
List Ids = query.list() ;
for (Iterator iterator = Ids.iterator(); iterator.hasNext(); iterator.next()){
query = session.createSQLQuery("select distinct rec_category, a_id from a_cdr where a_id in (select id from alerts where al_id = :aid)")
.setParameter("aid", Long.parseLong(Ids.get(0).toString())) ;
java.util.List result = query.list() ;
System.out.println("printing class object" +result.get(0).getClass()) ;
}
session.close() ;
Question:
result.get(0) is a object contain value rec_category and a_id. How can I fetch this variables ?
The result.get(0) returns an Object[] (in this case with 2 elements). So cast it first to Object[], then retrieve each element separately and cast them to their proper types.
Object[] foo = (Object[]) result.get(0);
System.out.println(foo[0] + " and " + foo[1]); // Then cast each one to their real types
Related
I have an object (A), that has a field that contains another object (B), and B has a field of long type. I want to be able to access B's long type field in a criteria query.
In the example code, we see how to get the field of an object, but is there a way to get objectA.objectB.field in a similar way as the example code looks like?
I have found this example code:
CriteriaQuery<Integer> criteria = builder.createQuery( Integer.class );
Root<Person> personRoot = criteria.from( Person.class );
criteria.selec(1)t( builder.max( personRoot.get( Person_.age ) ) );
criteria.where( builder.equal( personRoot.get( Person_.eyeColor ), "brown" ) );
Integer maxAge = em.createQuery( criteria ).getSingleResult();
Create join from the root by specifying the join type
Join<ObjectA, ObjectB> objectBJoin = personRoot.join("objectB", JoinType.INNER);
The answer is we can use multiple get functions inside of each.
Example:
criteria.where(builder.equal(ParentClass.get("ChildClass").get("FieldOfChildClass"), "value" ));
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());
}
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.
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,
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.