Extract data from an Object - java

I have a SQL query that returns a list of deals which have this structure : deal_id, value_1, value_2, ..., value 50
I put the result of this query in a list like this (using org.hibernate.SQLQuery) :
SQLQuery select = session.createSQLQuery(QUERY);
List result = select.list();
Then I use this loop to iterate through the results :
for (Object o : result) {
}
When debugging, o looks like this (one String, 50 BigDecimal) :
[SSA12325, 0, 1.012, 1.1235, ..., 0]
I want to extract the deal_id, how do I do that ?
I tried to convert o to a List, but I got a classCastException : [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

here your Object o is Array of Object because it contains all Objects such as String and Integer.
So, try:
Object[] objArray = (Object[]) o;
then do whatever you want to do with your array.

Related

Hibernate SQLQuery list method returns Object instead of object array

I have this strange behavior with Hibernate SQLQuery.list() method.
Following is the description of the issue:
I have a sql select query which retrieves only single column(group) from the database (i.e., select group from peopleGroup where groupid = 10)
And i'm recieving the result of the above list in List of Object array
i.e,
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Ideally, the result should contain a list of object arrays but when I inspect, 0'th index of the result contains String object instead of an Object array.
However if I use more than one column let's say 2 columns in the select clause of the query I was able to see that 0'th index of the result as Object array i.e., Object[2]={"group","groupid"};
How do I get the Object array even if I have only one column mentioned in the select clause of the query?
Docs states:
List list()
Return the query results as a List. If the query contains multiple
results per row, the results are returned in an instance of Object[].
Convert it by yourself, like so.
List<Object[]> l = new ArrayList<>();
for(Object o : query.list()) {
Object[] arr = {o};
l.add(arr);
}
you can create a object mapper like below code
public class QueryMapper {
private String group;
//setter and getter
}
And you have to change your code like below
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
List<QueryMapper> list = new ArrayList<QueryMapper>();
for(Object[] object: result){
QueryMapper queryMapper = new QueryMapper();
if(object[0]!=null){
queryMapper.setGroup((String)object[2]);
}
list.add(queryMapper);
}
All i wanted is to fix the ClassCastException which was caught during the assignment of result.get(0) to the container i.e., container = result.get(0);
Since the value returned by mentioned list() method contains object in case of single column in the select clause of the query and i won't be allowed to cast from certain object to Object[](Object array).
Instead i have tried a work around like below
Already existing code
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Object[] container = result.get(0);
now i have put condition like below to decide how to assign value to the Object[]
SQLQuery hQuery = session.createSQLQuery("select group from peopleGroup where groupid = 10");
List<Object[]> result = (List<Object[]>)hQuery.list();
Object[] container = null;
if(result.get(0) instanceof Object[])
container = result.get(0);
else {
container = new Object[1];
container[0] = result.get(0);
}
The above solution seems working in my case !

How to know the type of a native SQL query result in Hibernate?

I have a native SQL query in Hibernate. I get the query result by :
List l = query.list().
I know that each element of the list corresponds to a line of the result table. But what are the types of those elements ?
Java tells me they are of type : Object. Ok but I want more. Because I want to print the results in the Eclipse console. But for that, I have to know the types, I have to know what this list exactly contains.
Here is the result table of my query I get in SL Developer :
And know, I want to print all that data in Eclipse console
In Eclipse, I use Query query = session.createSQlQuery("my query");
List l = query.list();`
For information, here is the SQL query code :
The Object in the list is an array of Objects (one per column).
You have to iterate (that's for each row) then use the array of columns:
final List<Object> l = query.list();
for (final Object row : l) {
final Object[] columns = (Object[]) row;
// use columns[0], columns[1] etc
System.out.println(columns[0]);
}
If I've got your issue correct, try getClass().getName() methods, which'll give you runtime class of your object. More info here

Convert a List<Object> to List String

Query w=em.createQuery("SELECT ar.authorId.firstName,
count(ar) FROM Article ar
WHERE ar.categoryId.categoryText=:
categoryText GROUP BY ar.authorId");
w.setParameter("categoryText", categoryText);
List list1=w.getResultList();
System.out.println(list1.toString());
Whats the wrong. i get [[Ljava.lang.Object;#60a19573, [Ljava.lang.Object;#44a085e5]
I want to print the query like "name:"+firtname+"Articles:"+count(ar)
Implement toString() in that particular type SomeType
What you're getting back in your query is a List<Object[]> which is expected as per the spec. The first element in your array is the string ar.authorId.firstName and the second is a Long representing count(ar)
A String.format should work here for you:
for(Object[] objs : list1) {
System.out.println(String.format("name %s articles %s",objs[0],objs[1]);
}
for(Object objs : list1) {
System.out.println(String.valueOf(objs));
}
valueOf is an String method which helps to convert primitive data types to String.

Error in casting Object[] to byte[]

I want to read from database a pdf, which stores as BLOB and I want to get List<bytes[]>
session.beginTransaction();
final Criteria criteria = session.createCriteria(MyClass.class);
criteria.add(Restrictions.eq("id",id));
final ProjectionList projectionList = Projections.projectionList().add(
Projections.property("bdoc"));
criteria.setProjection(projectionList);
List<Object[]> list = criteria.list();
List<byte[]> listBytes = new ArrayList<byte[]>();
for (Object[] item : list) {
listBytes.add((byte[]) item[0]);
}
session.getTransaction().commit();
But I get an error in this line for (Object[] item : list) {
[ERROR] [B cannot be cast to [Ljava.lang.Object;
I've debugged and I do read data from database: my List<Object[]> list = criteria.list() is not empty.
But I can not convert from List<Object[]> to List<bytes[]>. What am I doing wrong? Help me please to resolve my problem.
B cannot be cast to [Ljava.lang.Object;
Means you are indeed getting bytearray and you are trying to convert it into Object array.
This problem is caused because Criteria.list() returns a raw List. As a result, you are able to write code that causes a ClassCastException. With a properly typed list, the compiler would prevent this.
As explained in the other answer, the text [B cannot be cast to [Ljava.lang.Object means that a byte[] is being cast to an Object[], which is not allowed.
This means that your list contains byte[] objects and you should declare it as such:
List<byte[]> list = criteria.list();
In addition, the contents of your for-loop now look incorrect:
listBytes.add((byte[]) item[0]);
Since item is now a byte[], it's not correct to cast a byte to a byte[]. Perhaps you need to remove the array index [0].

Why string is not printing correctly?

I have created a user type in oracle
create or replace type my_friend_list
is
table of
varchar2(100);
Now i have written a procedure which has a output parameter like this :
PROCEDURE friends_diff_prc
(
my_name IN VARCHAR2,
friend_i IN my_friend_list ,
good_friend_o OUT my_friend_list ,
best_friend_o OUT my_friend_list ,
isSuccess OUT NUMBER
);
I run it on SQLDeveloper And it is running correctly .
And it is giving me list both of my good friends and best friends.
But when i am calling it through JAVA Class which is extending StoredProcedure.
best_friend list is correcly coming but for the good_friend list it is printing
Ljava.lang.Object;#24342434,
Ljava.lang.Object;#243a243a,
Ljava.lang.Object;#24402440,
Ljava.lang.Object;#24462446
My java code to fetch this output arraylist is like this:
List<String> goodfriends = Arrays.asList((String[]) results.get("good_friend_o");
List<String> bestfriends = Arrays.asList((String[]) results.get("best_friend_o");
Why it is not giving correct result for good_friends ?
Thanks in advance.
Your Getting the answer as Array of String, and then storing in a String of List.. You cannot store the String[] into String straightly.
can you post the, java code for fetching and printing...
Try this code. This will print the strings
System.out.println("Printing goodfriends");
for (Object object : goodfriends) {
Object[] goodfriendsString = (Object[]) object;
for (Object object2 : objLocationVO) {
System.out.println(object2);
}
}

Categories