How to get attributes of an Object in Java? - java

I have a function that returns an Object
The toString() method shows that my object has two BigDecimal attributes. But I don't know how to get them in the code ?
My function uses hibernate to get results from a query is :
public Object executeQuery(final String sql) {
final Query query = getSessionFactory().getCurrentSession().createSQLQuery(sql);
return query.list().get(0);
}
Thank you.
-- Additional infos:
obj.getClass().getDeclaredFields(); // empty array []
obj.getClass().getName(); // [Ljava.lang.Object;
final BigDecimal b = (BigDecimal) obj[0]; //Compilation error: The type of the expression must be an array type but it resolved to Object

obj.getClass().getDeclaredFields() can help you. Generally learn reflection API. If you object bean you can also use Jackarta BeanUtils.

Judging from your comments, your Object is and Object array.
So you should first cast the result to an Object array:
Object[] obj = (Object[]) query.list().get(0);
Then, you should be able to access the first BigDecimal like that:
BigDecimal b = (BigDecimal) obj[0];
Probably, you want to add some exception handling.

It is not an Object, it is an Array of Objects.
BigDecimal firstColumn = (BigDecimal) ((Object[])query.list().get(0))[0];
BigDecimal secondColumn = (BigDecimal) ((Object[])query.list().get(0))[1];
That's all.

UPDATE:
You have a resultset with 2 columns.
Object[] result= query.list().get(0);
BigDecimal number1 = (BigDecimal) result[0];
BigDecimal number2 = (BigDecimal) result[1];

Get first what class name of that object by
System.out.println(obj.getClass());
Since you are running a sql query, result might be an Entity or Object[].
when you came to know retrieved object from query is an Object[] you can iterate like
if( obj instanceof Object[] ) {
Object[] objA = (Object[])obj;
for(Object atomicObj : objA ) {
System.out.println(atomicObj);
}
}
It works for all elements which presents in object array. This time you may get BigDecimal, next query might return a String and BigDecimal.

Related

getting class cast exception

i just want to pass sql query builder query in JPA like
public List<QueryBuilder[]> getQueryBuilder(String query) {
EntityManager em = getEntityManager();
try {
Query q = em.createNativeQuery(query);
List<QueryBuilder[]> queryBuilderList = (List<QueryBuilder[]>) q.getResultList();
return queryBuilderList;
} finally {
em.close();
}
}
the query
SELECT p.*,c.*,e.*,pmh.*,rk.*
FROM patient p, case1 c, episode e, personal_medical_history pmh, reproductive_history rh
WHERE c.Clinical_Stage = 'IA2'
AND c.Patient_Id = p.Patient_Id
AND e.Case_Id = c.Case_Id
AND pmh.Patient_Id = p.Patient_Id
AND rh.Patient_Id = p.Patient_Id
GROUP BY p.patient_Id
and on service i do somthing like
List<QueryBuilder[]> list = builderJpaController.getQueryBuilder(query);
for (QueryBuilder[] queryBuilders : list) {
for (QueryBuilder queryBuilder : queryBuilders) {
System.out.println("queryBuilder Value "+queryBuilder.getRace());
}
}
but i'm getting class cast exception by doing above code please help
below is the exception
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.medikm.entity.QueryBuilder;
at com.medikm.servlet.QueryBuilderServlet.getQueryJson(QueryBuilderServlet.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
The problematic line is:
List<QueryBuilder[]> queryBuilderList = (List<QueryBuilder[]>) q.getResultList();
You are assuming that the untyped list returned by q.getResultList() is a list of QueryBuilder[]s. Actually it is an Object[]. However, this compiles because q.getResultList() has a raw return type, so the compiler can't tell that this is unsafe.
Then, when consuming the elements of the list, you attempt to cast an Object[] to a QueryBuilder[] - which can't be done.
It is very unlikely that the elements of rows returned by a query would themselves be QueryBuilder instances - they are much more likely to be "plain old" values, like Strings, numbers etc.
(I say "very unlikely" because I'm not familiar with JPA - I am just going off what I expect a persistence API to do)
You need to rethink your expectations of what you are trying to do here.
Note that even if the elements of the Object[] were instances of QueryBuilder, you can't cast a Superclass[] reference to a Subclass[] reference - there is no superclass/subclass relationship between array types.
You need to explicitly cast each of the individual elements:
Subclass[] castArray(Superclass[] arr) {
Subclass[] subclassArr = new Subclass[arr.length];
for (int i = 0; i < arr.length; ++i) {
subclassArr[i] = (Subclass) arr[i];
}
return subclassArr;
}

issue while converting BigDecimal to Integer

I'm facing problem while converting Big Decimal to Integer.
My process description is, First I will be sending List of Integers into a DAO method to validate whether the integers are valid to proceed further. Then the valid List of Integers are processed in another place.
Core process
List<Integer> payments = DAO.checkStatus(payments); //payments is List of Integer
if(payments!=null){
//Do some other operation
DAO.changeStatus(payments); //Here payments is List of Integer which we got from above
DAO method implementation
checkStatus(List<Integer> payments){
List<Integer> FinalPayments = null;
//I have Hibernate query to get the details from Database
String HQL_Query = "select A.PY from T_Status A where A.status = 4 and (A.PY=:payments)";
Query query = session.CreateQuery(HQL_Query);
FinalPayments = query.list();
return FinalPayments;
}
In the DataBase PY column is a BigDecimal one. In table its defined as NUMBER. type. While execution of the query i'm getting BigDecimal values for FinalPayments list. There was no error/exception. The BigDecimal value is returned properly.
In core process, after the 1st method:
if(payments!=null){
//we're doing something with List of Integer payments right?
//It is passed to 2nd method.
changeStatus(List<Integer> FinalPayments){
String HQL_Query="update T_Status A set A.status = 6 where (A.PY:=FinalPayments)";
Query query = session.CreateQuery(HQL_Query);
query.setParameter("FinalPayments", FinalPayments); //Here i'm getting error
List<Integer> paymentsAfter = query.list();
}
The error is:
cannot cast java.math.BigDecimal to java.lang.Integer
Between 1st and 2nd method i tried to convert BigDecimal to Integer. But can't convert Integer list to Integer again.But i need those to be in the format of Integer to process 2nd method. Please help on this..
Use the intValue() method on your BigDecimal object to get its int value.
I'm not sure I understand your question but if you have a BigDecimal and you want a Integer you can use either intValue of intValueExact.
E.g.
List<BigDecimal> decimals = ...
List<Integer> ints = decimals.stream().map(BigDecimal::intValue).collect(Collectors.toList());

extract Object parameters to POJO

How is it possible to get the [0], ..., [4] parameter's values of the Object below ?
The Object you see below is a result from EntityManager.createNativeQuery().
I would like to use the values to create a POJO. I know I could use EntityManager.createNativeQuery("SQL Query", MyPOJO.class), but it returns POJO only with ID, all other variables are null?! and I am interested in how to get object's parameters.
It's not possible to cast returned object to MyPOJO, because MyPOJO is a JPA Entity with references to another JPA Entities, and the returned object contains only IDs of another JPA Entities.
Thank you!
I solved it the following way:
Let nativeQuery to return me result as a List of Object[] and access the Object's values through index.
Here is my solution:
List<Object[]> executeObjects = null;
Query query = mgr.createNativeQuery("SQL Query");
executeObjects = (List<Object[]>) query.getResultList();
for (Object[] object : executeObjects) {
Long id = new Long((Integer) object[0]);
Long id2 = new Long((Integer) object[1]);
String desc = (String) object[2];
...
...
}

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.

getting class cast exception while storing the content of list into set

I have fired the below hibernate query which is fetching the data perfectly but the return type is of List as shown below..
public List<Object[]> Extractingc()
{
Criteria criteria = session.createCriteria(IDetails.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("ter")); //is of string type
proList.add(Projections.property("sem")); //is of string type
proList.add(Projections.property("tid")); //is of long type in pojo *******
proList.add(Projections.property("def")); //is of string type
criteria.setProjection(proList);
List<Object[]> settlementIdList = criteria.list();
return sst;
}
now the problem comes in java code is that i am putting the result of above method in an an list further in code as shown below...
List<Object[]> ioaist = = ioabookandinstrumenthome.Extractingc();
now further i have created a set as in set i want to store the combination of all 4 parameters that is sem+tid+ter+def in the set that is I am doing as shown below...
Set<String> st = new HashSet<String>();
for (Object[] arr : ioabookandinstrumenthomelist)
{
s=((String) arr[0]+ (String) arr[1]+ (String) arr[2]+ (String) arr[3]); //*** getting class cast exception
st.add(s);
s=null;
}
but I am getting class cast exception as my parameter tid is long type which is not converted in string
Yes, you can't cast longs to Strings. You can however use String.valueOf()

Categories