I am trying to retrieve the values from database and storing it in List,
The data's are retrieved and working properly, But when i convert the List into Object<pojo class> i am getting an Exception ,
My Code is
Query qry=session.createQuery("select personaldetails.fname,personaldetails.lname from Personaldetails as personaldetails where refId=1001");
List<Personaldetails> l=(List<Personaldetails>)qry.list();
session.getTransaction().commit();
session.close();
System.out.println("--->"+l.size()); //List 'l' holds the values from DB
Personaldetails p; //This is an pojo class
p=(Personaldetails)l.get(i); //Here i am getting the exception here
System.out.println("Person name "+p.getFname());
In above mentioned line i got Exception as ClassCastException , i don't know why, i tried it shows no error while compiling.
Any suggestion will be appreciated....
I see that you are doing selective query - that is select fname, lname
select personaldetails.fname,personaldetails.lname from Personaldetails as personaldetails where refId=1001
which returns List<Object[]> where each elements in array represents the 2 column values
List will be something like [{"Fname1", "LName1"}, {"Fname2", "Lname2"}]
So ClassCastException is due to the fact that you are converting Object[] into PersonDetails.
To expect List<PersonDetails> as the result, you can use query like
select from Personaldetails as personaldetails where refId=1001
Or you can iterate through the List<Object[]> and construct PersonDetails yourself
for(Object[] arr : l) {
PersonDetails p = new PersonDetails();
p.setFName(arr[0]);
p.setLName(arr[1]);
}
I prefer the first approach
In above mentioned line i got Exception as ClassCastException , i
don't know why, i tried it shows no error while compiling.
When you explicitly cast, the compiler cannot help you. Type casting is your way to tell the compiler that you know this type is some other type. The compiler trusts that you know what you're doing.
The real question here is how does the list get created?
Query qry=session.createQuery("select personaldetails.fname,personaldetails.lname from Personaldetails as personaldetails where refId=1001");
List<Personaldetails> l=(List<Personaldetails>)qry.list();
How do you know that qry.list() returns a List? You just ran a SQL statement and jumped to a List. Since the cast to List works fine, clearly a List is in fact returned (though due to type erasure, we don't know if it in fact only holds Personaldetails objects).
It must return a List. #sanbhat seems to have pointed you to the right structure for that method. I don't have any experience with Hibernate.
Related
I am using an hibernate NQL query which fetches me two columns :
SELECT object_name,
object_name_location
FROM dbo.object_stacks
WHERE object_id IN (SELECT thumb_nail_obj_id
FROM dbo.uois
WHERE Upper(NAME) LIKE Upper('%testobj%'))
When I select only one column i.e only object name - everything works fine but with two columns I am getting an error
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
java.lang.String
at run time when I try to display result from the list. I tried using String array in the list as well but it doesn't work. Below are my code snippets which give error :
When I use only List :
List<String> Thumbnailpaths = pathquery.list();
System.out.println(Thumbnailpaths.get(i).replace("\\", "\\\\"));
No error at compile time also nothing if leave it as it is but above line to display gives classcast exception.
When I use List array :
List<String[]> Thumbnailpaths = pathquery.list();
System.out.println(Thumbnailpaths.get(i)[0].replace("\\", "\\\\"));
Here again classcast exception at runtime
Also Criteria.ALIAS_TO_ENTITY_MAP doesn't help at all as it makes logic much more complex. I just need 2 column values from a database table.
Please let me know if there is any solution to fetch multiple column results in NQL and then put in list.
Note : Looks like here generics are not displaying and only List is being written in my code snippet
Yes, hibernate will return the Object arrays (Object[]) for this case - return multiple columns. but you still can using the "Entity queries" to return a entity objects rather then the "raw" value.
Unfortunately, Hibernate doesn't provide a standard way to retrieve the results for columns of table and store directly to Entity Object.You have to manually parse the data fetched by your query.
The hibernate query will return List of Object Array i.e. List<Object[]>.
Object[] will contain data from your columns. List is nothing but rows retrieved by query. In your case you can refer following code :
List<Object[]> Thumbnailpaths = pathquery.list();
for(Object[] objArr : Thumbnailpaths)
{
String objName = (String)objArr[0];
String objNameLocation = (String)objArr[1];
System.out.println(objName + " : " +objNameLocation);
}
Above code will help you parse the object[]
I'm coming back to Java after a few years away and this is my 2nd day looking at hibernate and don't fully understand it yet.
I have the following criteria which is performing a join:
Criteria cr = s.createCriteria(Bla.class, "bla");
cr.setFetchMode("bla.nodePair", FetchMode.JOIN);
cr.createAlias("bla.nodePair", "node_pair");
cr.add(Restrictions.in("bla.blaName", (List<Bla>) getBlas()));
ProjectionList columns = Projections.projectionList()
.add(Projections.property("node_pair.priNode"))
.add(Projections.property("bla.blaName"))
.add(Projections.property("node_pair.secNode"))
.add(Projections.property("bla.port"));
cr.setProjection(columns);
List<Object[]> list = cr.list(); // Exception occurs here
This is creating as far as I can tell a valid SQL query and exactly what i'm after.
However, when I try to generate a list of results cr.list(); I get:
java.lang.ClassCastException: com.some.package.domainobject.Bla cannot be cast to java.lang.String
How should I construct my List. Any pointers much appreciated.
In Criteria API, the Exception is always(?) thrown when attempting to get the results.
In your case, the problematic line is probably
cr.add(Restrictions.in("bla.blaName", (List<Bla>) getBlas()));
You seem to check if a java.lang.String is part of a Collection<Bla>.
If your equals and hashcode methods in Bla use the blaName field, you should be able to use
cr.add(Restrictions.in("bla", (List<Bla>) getBlas()));
Otherwise, implements a getBlasNames() function which returns a List<String>
Hi to all i'm new in J2EE world.
I'm trying to use #Namequery to get a List of String from my model(the class is called Element), in this case the attribute name.
Why when I use #NamedQuery(name="Element.findAllNames",query="SELECT e.name FROM Element e")
and I use it on my ElementMgrBean using:
public List<String> getAllElementsName() {
return em.createNamedQuery(Element.FIND_ALLNAMES,Element.class).getResultList();
}
the result appears to be a list of elements instead of a list of String as I expected.
Someone can explain me why Java says: "Type mismatch: cannot convert from List of Element to List of String"??
PS: I have defined:public static final String FIND_ALLNAMES = "Element.findAllNames";
When you write em.createNamedQuery("NameOfNamedQuery", MyClass.class), you say you want to fetch MyClass instances (in your query MyClass==Element). The problem is now, that your query SELECT e.name FROM Element e returns Strings instead of Element instances (as the e.name fields are of type Strings).
In order to correct the problem you either correct the call to em.createNamedQuery(Element.FIND_ALLNAMES, String.class) (the preferred solution, as it returns a TypedQuery<String> instance), or you remove the second parameter: em.createNamedQuery(Element.FIND_ALLNAMES) (in this case you are not type-safe anymore, as it returns a Query instance).
I have written a code like this to fetch data from database using HQL:
Query qr=sess.createQuery("select i.contract_Vcode,i.installment_date from Installment i where i.vcode=:instalVcode").setParameter("instalVcode", installVcode);
qr.getNamedParameters();
List<Installment> li=null;
li=qr.list();
int coVcode=li.get(0).getContract_Vcode();
As I know the contract_Vcode is an integer. But when I want to run it, the followed error happens:
Error invoking Action using Hibernate Core Session / Transaction injection
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to information.Installment
More over when I want to see the exact element like this,
System.out.println("contract installDate is: "+li.get(0).getContract_Vcode());
Same error happens. How can I fix this?
You're currently only querying two parts of an installment. If you want to fetch the whole thing, I'd expect something like:
Query qr = sess.createQuery(
"select from Installment as i where i.vcode=:instalVcode")
.setParameter("instalVcode", installVcode);
If you fetch multiple properties (instead of whole entities), you just get back an Object[] for each row in the results.
So you could use your original query, but:
List<Object[]> li = qr.list();
int coVcode = (Integer) li.get(0)[0]; // 1st column of 1st row
I have a problem using RowMappers with JDBC (especially ParameterizedSingleColumnRowMapper) :
I am querying a list of existing ids from a database with the following :
List<Long> existingIds = DS.getJdbcTemplate().query(sql,
new ParameterizedSingleColumnRowMapper<Long>());
The only problem is that my list sometimes does not contains long as expected :
// for some value...
System.out.println(existingIds.get(0) instanceof Long); // return FALSE
System.out.println((Object)existingIds.get(0) instanceof Integer); // return TRUE
I could just go through existingIds and recast the values to long but I was expecting the row mapper to do that (I guess ParameterizedSingleColumnRowMapper is using getLong or something like that and usually it tries to cast to the desired value).
Do you have any explanation or ideas to solve that ?
Thanks in advance for your help.
You need to do ParameterizedSingleColumnRowMapper.newInstance(Long.class). Just creating a new instance directly means it doesn't know the type correctly (it can't infer it from the generics because they get erased at compile time) so it probably just does .getObject() which will be at the mercy of the JDBC driver.