Using an object that extends HibernateDaoSupport, I ran a query using this right here:
List<Object> trialList2 = getSession().createSQLQuery(trialQuery2).list();
Where trialQuery2 is just some query that returned a single row. I got back a list with one Object on it, which when inspected in Eclipse looks like this:
[some, random, data]
I'd like to create an Object that can accommodate what I got back from the query, but a simple Javabean object that can has those fields doesn't seem to work. Does anyone know what kind of object I would have to make to be able to access those values?
It would be actually Object[] not Object
List<Object[]> trialList2
Based on columns in your select query, you get values from index
Let us say, if your query is select firstname, lastname from employee;
Object[0] would be firstname
Object[1] would be lastname.
As per documentation :
These will return a List of Object arrays (Object[]) with scalar values for each column in the table
U can replace any class name for BEANCLASSNAME
List<BEANCLASSNAME> trialList2 = getSession().createSQLQuery(trialQuery2).setResultTransformer(new AliasToBeanResultTransformer(BEANCLASSNAME.class)).list();
Related
I have a situation where I need to return only few fields of a POJO.
Here is a SOF Question: retrieve-single-field-rather-than-whole-pojo-in-hibernate question regarding the same, but few things still seems to be obscure.
1) The answer suggests to use -
String employeeName = session.createQuery("select empMaster.name from EmployeeMaster empMaster where empMaster.id = :id").setInteger("id",10).uniqueResult();
So, here is my concern - Every pojo field is normally private, so "empMaster.name" will simply not work. And am not sure if empMaster.getName() is the solution for this. Will calling the getter methods work?
2) If i am querying multiple fields, (which is my case) (assuming getter methods work) the query will be some thing like -
List<String> employeeDetails = session.createQuery("select empMaster.getName(), empMaster.getDesignation() from EmployeeMaster empMaster where empMaster.id = :id").setInteger("id",10).uniqueResult();
Note the return type has changed from String to List<String>.
2(a) Hope this is right?
2(b) what if i am interested in age/salary of employee which will be of int type. I think the return type will be List<String> or List<Object>. Well any how in the application i can recast the String or Object to the proper type int or float etc. So this should not be a problem.
3) Now what if I am querying multiple employee details (no where clause), so the query will be something like - (not sure if the part of query after from is correct)
List<List<<String>> employeesDetails = session.createQuery("select empMaster.getName(), empMaster.getDesignation() from EmployeeMaster;
Anyway, point here is to emphasise the change in the return type to : List<List<<String>> employeesDetails. Does it work this way ???.
(The question quoted above also has answers pointing to use Projections. I have questions about it but will post them on another question, don't want to mixup.)
I will list the points in the order you mentioned them:
The query has nothing to do with the POJO's field visibility. You are doing a simple query to the database, as if you were doing a query using SQL, and columns in a table have nothing to do with the fact that their mapped POJOs' fields in an application are public or private. The difference is only the language that you're using: now you're using the Hibernate Query Language (HQL), which allows you to express your query with respect to the POJOs' definitions instead of the database's tables' definitions. In fact, doing
session.createQuery("select empMaster.getName() from EmployeeMaster...");
will throw a syntax error: there can be no parenthesis in an object's field name.
By the way, you have to parse your query result to a String, otherwise there would be a compiler semantics error.
String name = (String) session.createQuery("select empMaster.name from EmployeeMaster...").setYourParameters().uniqueResult();
When you do a query whose SELECT clause contains more than one field, and you call uniqueResult(), you're obtaining an array of Objects (Object[]). You iterate through each element in the array and cast it to the corresponding type.
First of all, you probably forgot to add a .list() method call at the end of your query.
session.createQuery("select empMaster.name, empMaster.designation from EmployeeMaster").list();
Otherwise, the query will not be executed, and you would just have a QueryImpl object waiting to be triggered.
Now, when you're expecting multiple results in your query and selecting several fields, you're getting back a List<Object[]>. The elements of the list will be the array of fields for a specific record, and the array per se will be the fields.
I want to join two table:
T1:id,name,email
T2:id,address
to join I am doing this:
String hql="select sd.name,tt.name from T1 sd,T2 tt where sd.id=tt.id";
Query q=ss.createQuery(hql);
List l2=q.list();
Object o1=l2.get(0);
System.out.println("-----------");
System.out.println(o1.toString());
System.out.println("-----------");
It is returning object but dont get how to retrieve the values as returned object is not entity object.
Every result is an Object Array.The Array's size is the select columns
List l2=q.list();
Object[] o1=(Object[])l2.get(0);//The size is should be 2
System.out.println(o1[0]);
System.out.println(o1[1]);
You have to cast the Object's in the List to your specific type, Hibernate does not know the type. See What is the "proper" way to cast Hibernate Query.list() to List<Type>? and Hibernate query for selecting multiple values
it will return array of Object which you need to typecast as per your select values like name etc.
List<Object[]> values= (List<Object[]>)q.list();
for(Object[] val: values){
....
//your specific type values
}
Another option is creating a view with your joined tables, then, create hibernate entity base on that view
I have set up a Cassandra connection through Java driver. And I want to retrieve an entire row as a collection. I want to get rid of using getString() or getInt() always. When I give a query saying select all columns in the users table using CQL. the entire result should be sent to a collection rather than a string. How do I achieve this?
I have done the following to retrieve the columns. It gives me the proper results. But I want to retrieve the entire row as a collection.
Outside the for loop I want to retrieve these fields as one object. How do I do this??
String name=null;
String age=null;
ResultSet results = session.execute("SELECT * FROM admin.users");
for (Row row : results) {
name=row.getString("firstname");
age=row.getString("age");
System.out.println("name::"+name);
System.out.pintl("age::"+age);
}
If you want to obtain all fields in a collection you could use getMap(..) function and you will get a Map with keys and values.
On the other hand, check new object Mapping API since version 2.1 and you can map a class directly from ResultSet with annotations in your entity class.
My retrived data from SQL looks like this
ID Name
1 abc
2 xyz
3 def
Which Java collection variable shall I use to store and retrieve them based on postion alter.
I tried with list...But is was only including ID values,not the Name column.
Any help would be highly Appriciated
You might want to use Map collection which is useful to store key value pairs where Id is your key and value is your name.
Map<Long,String> map = new HashMap<Long,String>();
Like Suresh ATTA said Map is the best solution for this scenario. But in case you are going to get more columns from the DB, then it is better if you write a class around it.
An object of that class will represent a row, and the list of object will represent the result set you queried for.
For your current scenario it looks like:
class Name {
String ID;
String Name;
}
List<Name> allNames = // query from DB and resultset mapped to classes properly.
allNames.get(0) will give you the first row, and allNames.get(allNames.size()-1) will give you the last row.
I use hql to query from database. first query returns a list of objects like this
see image:
as you can see, the field names of retrieved objects are obvious (ID, TIMESTAMP, ...)
but in the second query, what I get, is this:
see image:
and I need to change field names ([0] to ID , 1 to TITLE, ...)
any solutions?!
Create a simple data holding object that contains your needed data.
Fill your data into such an object
Add this object to a new list/array
View the debugger on this list again