The following code snippet works as expected, returning a list containing a dozen rows.
String hql = "select assetDate, sum(variable) as variable from Table where assetDate >= '30-JUN-19' and assetDate < '30-JUN-20' and ver= '"+ver+"' group by assetDate order by assetDate";
List results = session.createQuery(hql).list();
This code, however, returns an empty list, but no errors.
String hql = "select assetDate, sum(variable) as variable from Table where assetDate >= '30-JUN-19' and assetDate < '30-JUN-20' and ver= :ver group by assetDate order by assetDate";
List results = session.createQuery(hql).setString("ver",ver).list();
I cannot understand what might be causing the difference here.
In the log, I can see:
binding parameter [1] as [VARCHAR] - [the correct value]
So it looks like the variable is being bound properly, but since the output is incorrect, it clearly isn't. Does anyone have any idea what might be happening internally to cause this difference?
The column ver in the source table is of type CHAR( 20 BYTE), which is the only thing I can think of that might cause a problem, but even that seems somewhat unlikely.
Related
I am running a simple insert using jooq:
InsertValuesStep6<...>
insertInto =
withContext()
.insertInto(
MyTable,
MyTable.ID);
for (Integer id : ids) {
insertInto = insertInto.values(id);
}
insertInto.execute();
I simplified it a bit for the question, there are couple of more fields in each row.
It usually works fine, but once in a while get an exception: org.postgresql.util.PSQLException: No value specified for parameter 1.
So I suspect it's not a syntax issue but scale issue.
Maybe the actual query is trimmed by jooq somehow?
I am running different JPA queries in the form of
Float getDepositVolumeByDepositIdDepositAndSpeciesIdSpeciesAndRangeIdRangeAndSubRangeIdSubrange(Long idDeposit, Long idSpecies, Long idRange, Long idSubRange); // this is one of the methods that fail
#Query("select stock.depositVolume from Stock s where s.deposit.idDeposit = ?1 and s.species.idSpecies = ?2 and s.range.idRange = ?3 and s.subrange.idSubrange = ?4")
Float getVolumeByDepositIdDepositAndSpeciesIdSpeciesAndRangeIdRangeAndSubRangeIdSubrange(Long idDeposit, Long idSpecies, Long idRange, Long idSubRange); // this one is just for ilustrative purpose and throws the exact same error
These two queries being just some of those that should return one row. Although the database has only one row corresponding to the data provided to the query, hibernate throws the following error message:
Result returns more than one elements
I have turned on hibernate query log and the query generated is the following for the first method:
select stock0_volume_stock as col_0_0_ from public.stock stock0_ where stock0_.id_deposit = ? and stock0_.id_species = ? and stock0_.id_range = ? and stock0_.id_sub_range = ?
with the correctly bound parameters. I ran the query on PostGres and it returns only one row with a float.
It is worth mentioning that my class declaration is:
public interface StockRepository extends QueryDslPredicateExecutro<Stock>, JpaRepository<Stock, long>
What I have ended doing is change those methods into
List<Stock> findFirstByDepositIdDepositAndSpeciesIdSpeciesAndRangeIdRangeAndSubRangeIdSubrange(Long idDeposit, Long idSpecies, Long idRange, Long idSubRange); // now it justly returns only one row, the first one
I usually suppose, and certainly on previous projects this was the behavior observed, that the first method should map the only result fetched from the database into the expected float
I am very interested what is the explanation of this behaviour.
If you do SELECT some-column FROM some-table WHERE... there is no way for jpa/hibernate to know that only one row matches the condition, on the contrary it must assume that many rows are returned and my guess is that it always uses the same logic for a query like this (assuming multiple rows) and that the error message is misleading here.
To get one row you would need a query with an aggregate function like SUM or COUNT as the only element in the SELECT clause. Maybe for fun you could try to use SUM in your original query and see if it returns the expected result.
Maybe this is more suitable as a comment than an answer but it felt like to long for a comment
Hi can anyone tell me why this java query is failing?
Query q = entityManager.createNativeQuery("SELECT m.* FROM MdmAudit m WHERE m.correlationID = :correlationId AND m.verb = :verb", MdmAuditDAO.class);
//Query q = entityManager.createNamedQuery("MdmAuditDAO.GetData");
q.setParameter("correlationId", resp.getHeader().getCorrelationID());
q.setParameter("verb", resp.getHeader().getVerb());
long result = (long) q.getFirstResult();
The namedQuery:
#NamedQuery( name="MdmAuditDAO.GetData", query="SELECT m FROM MdmAuditDAO m WHERE m.correlationId = :correlationId AND m.verb = :verb")
public class MdmAuditDAO implements Serializable {
I have getters and setter in my MdmAuditDAO class, and I have checked the naming of the variables, and they are identical as in the NamedQuery, so the problem does not lie there.
My problem is that I have three entries in my database, I should at least get one answer back but I get 0 in my result.
MdmAuditDAO is defined in my persistence.xml and in my ehcache.xml. So why is it that the result I get returned is 0? I have also tried to get an object returned or a list of objects, and it is the same result, nothing gets returned, but when I run my query in my mssql database I get results see picture below. It has nothing to do with the m.* I aslo get results when I use that in my SELECT statement.
EDIT 1: This is what I get from my hibernate log, and I do not know how to read this?
Hibernate:
select
mdmauditda0_.id as id1_7_,
mdmauditda0_.correlationID as correlat2_7_,
mdmauditda0_.messageID as messageI3_7_,
mdmauditda0_.meter_no as meter_no4_7_,
mdmauditda0_.noun as noun5_7_,
mdmauditda0_.payload as payload6_7_,
mdmauditda0_.source as source7_7_,
mdmauditda0_.subtype as subtype8_7_,
mdmauditda0_.time as time9_7_,
mdmauditda0_.verb as verb10_7_
from
MdmAudit mdmauditda0_
where
mdmauditda0_.correlationID=?
Anything I have to set, to get more information? I am using the following jars
And my java version is 1.7.0_79.
I found the solution http://www.objectdb.com/api/java/jpa/Query/getFirstResult returns the position of the first element, but I was a bit confused by the phrase
Returns 0 if setFirstResult was not applied to the query object.
Could not get my head around it to make any sense of it.
My solution now is that I just return a list of objects
Query q = entityManager.createNativeQuery("SELECT m.* FROM MdmAudit m WHERE m.correlationId = :correlationId AND verb = :verb", MdmAuditDAO.class);
//Query q = entityManager.createNamedQuery("MdmAuditDAO.GetData");
q.setParameter("correlationId", resp.getHeader().getCorrelationID());
q.setParameter("verb", resp.getHeader().getVerb());
List<MdmAuditDAO> mdmAuditList = q.getResultList();
And then it works fine and I get results. So instead of the the result == 0 check I am doing later in my code I just do a NULL and isEmpty() check instead().
Side note: I have not tried to delete entries and then see what the result would be then in the q.getFirstResult() call but that would be a possibility and see what i get returned and then check on that value, properbly null?
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 have this method to call a stored function from ORACLE, in java (spring) - using entity manager + createNativeQuery ..
(...)
String set_professional = "{? = call
pk_backoffice.set_professional(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?}";
//32 parameters IN
query = entity.createNativeQuery(set_professional);
(...)
And everytime I try to test it, it shows:
Positional parameter does not exist: 31 in query: {? = call (...)
But do I have something at position 31..it exists..
query.setParameter(31, prof.getFax()); // fax
Also, I started the parameters at 1 cause in previous exceptions it said it was 1-based
I've tried with a string and a null value instead of the get, still the same outcome..
About the query, I also counted the ? many times, so I'm sure it has 32 (for parameters) + 1(return - first ?)...
Can anyone help?
Found a solution, I replaced all ? for variables, even the first one, and the error disappeared.