I am using Spring Boot endpoints to return results from database queries. It works fine when using getResultList() on the TypedQuery. However I know I will have to managed very large data sets. I am looking into using ScrollableResults via hibernate but I cannot figure out how to actually reference the contents of each row.
StatelessSession session = ((Session) entityManager.getDelegate()).getSessionFactory().openStatelessSession();
criteriaQuery.multiselect(selections);
criteriaQuery.where(predicates.toArray(new Predicate[]{}));
Query<?> query = session.createQuery(criteriaQuery);
query.setMaxResults(5);
query.setFetchSize(1000);
query.setReadOnly(true);
ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
while(results.next()){
Object row = results.get();
}
results.close();
session.close();
I have tried results.get(0), results.get(0)[0], results.getLong(0), Object[] row vs Object row, etc. With and without toString() on all of the options. Nothing I do gets more out of the row than the java object reference. I've tried casting as well and get a "cannot cast error". Sometimes I get an error, "query specifies a holder class". Not sure what that means because my criteria query is built by joining 1 or more entities where the entities and selected columns are not known before hand. So I am not actually specifying a class. They entities and selects are specified by user input. Any thoughts? Thanks!
UPDATE:
I can do System.out.println(scroll.getType(0)); and in this case observe a long.
But when I try to save that long (.getLong(0)) I get the error, "query specifies a holder class". Or again the cannot cast error.
Got it figured out. queryDetails is a CriteriaQuery<Tuple>
StatelessSession session = entityManagers.get("DatasourceName").unwrap(Session.class).getSessionFactory().openStatelessSession();
Stream<Tuple> resultStream = session.createQuery(queryDetails)
.setReadOnly(true)
.setMaxResults(100)
.setFetchSize(1000)
.setCacheable(false)
.getResultStream();
Iterator<Tuple> itr = resultStream.iterator();
while (itr.hasNext()){
//Get the next row:
Tuple row = itr.next();
}
A CriteriaQuery that uses multiselect produces an Object[] or javax.persistence.Tuple as result type. Maybe you should try debugging to see the actual object type and from there you can work further.
If you are processing and returning all rows anyway, there is no need to use the ScrollableResults API as you will have to create objects for all rows anyway. If your use case is to do some kind of aggregation, I would recommend you use an aggregate function instead and let the database do the aggregation.
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 have below code in my DAO:
String sql = "SELECT COUNT(*) FROM CustomerData " +
"WHERE custId = :custId AND deptId = :deptId";
Query query = session.createQuery(sql);
query.setParameter("custId", custId);
query.setParameter("deptId", deptId);
long count = (long) query.uniqueResult(); // ERROR THROWN HERE
Hibernate throws below exception at the marked line:
org.hibernate.NonUniqueResultException: query did not return a unique result:
I am not sure whats happening as count(*) will always return only one row.
Also when i run this query on db directly, it return result as 1. So whats the issue?
It seems like your query returns more than one result check the database. In documentation of query.uniqueResult() you can read:
Throws: org.hibernate.NonUniqueResultException - if there is more
than one matching result
If you want to avoid this error and still use unique result request, you can use this kind of workaround query.setMaxResults(1).uniqueResult();
Hibernate
Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);
"findTop"!! The only one result!
I don't think other answers explained the key part: why "COUNT(*)" returns more than one result?
I just encountered the same issue today, and what I found out is that if you have another class extending the target mapped class (here "CustomerData"), Hibernate will do this magic.
Hope this will save some time for other unfortunate guys.
Generally This exception is thrown from Oracle when query result (which is stored in an Object in your case), can not be cast to the desired object.
for example when result is a
List<T>
and you're putting the result into a single T object.
In case of casting to long error, besides it is recommended to use wrapper classes so that all of your columns act the same, I guess a problem in transaction or query itself would cause this issue.
It means that the query you wrote returns more than one element(result) while your code expects a single result.
Received this error while doing otherwise correct hibernate queries. The issue was that when having a class extend another hibernate was counting both. This error can be "fixed" by adding a method to your repository class.
By overriding the class count you can manually determine the way this is counted.
#Override
public Integer count(Page<MyObject> page) {
// manual counting method here
}
I was using JPQL and wanted to return Map. In my case, the reason was that I wanted to get Map<String, String>, but had to expect List<Map<String, String>> :)
Check your table, where one entity occurring multiple time's.
I had the same error, with this data :
id
amount
clientid
createdate
expiredate
428
100
427
19/11/2021
19/12/2021
464
100
459
22/11/2021
22/12/2021
464
100
459
22/11/2021
22/12/2021
You see here clientid occurring two times with 464.
I solved it by deleting one row :
id
amount
clientid
createdate
expiredate
428
100
427
19/11/2021
19/12/2021
464
100
459
22/11/2021
22/12/2021
I have found the core of the problem:
result of SELECT COUNT(*) can be a list, if there is a GROUP BY in the query,
and sometimes Hibernate rewrite your HQL and put a GROUP BY into it, just for fun.
Basically your query returns more than one result set.
In API Docs uniqueResult() method says that
Convenience method to return a single instance that matches
the query, or null if the query returns no results
uniqueResult() method yield only single resultset
Could this exception be thrown during an unfinished transaction, where your application is attempting to create an entity with a duplicate field to the identifier you are using to try find a single entity?
In this case the new (duplicate) entity will not be visible in the database as the transaction won't have, and will never be committed to the db. The exception will still be thrown however.
Thought this might help to someone, it happens because "When the number of data queries is greater than 1".reference
As what Ian Wang said, I suspect you are using a repository from spring. And a few days ago you just copy past a class and forgot to delete it when it is finally unused. Check that repository, and see if there is multiple same class of table you use. The count is not the count of rows, but the count of the table problem.
This means that orm technology is not preprogrammed to give you which results you are looking for because there are too many of the same results in the database. for example If there is more than one same value in my database and I want to get it back, you will encounter the error you get with the select query.
For me the error is caused by
spring.jpa.hibernate.ddl-auto=update
in application.properties file replacing it with
spring.jpa.hibernate.ddl-auto=create solved the issue, but it still depends on your needs to decide which configuration you need in your project, for more insights on the topic check this.
First you must test the query list size; here a example:
long count;
if (query.list().size() > 0)
count=(long) criteria.list().get(0);
else
count=0;
return count;
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.
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