conversion from int to DATE is unsupported on null date - java

I believe this has been a bug/problem in SQL 2000/2005 ... If my results have null on DATETIME column, i get
com.microsoft.sqlserver.jdbc.sqlserverexception:
the conversion from int to date is unsupported
when i use sql.getDate("ColumnName") ...
Any solutions to this?
[EDIT]
Hi all thanks for your inputs, below is my SQL query
select p.planno as PlanNumber,
t.TrancheID as TrancheID,
t.tranchestartdate as TrancheStartDate,
t.tranchereasoncode as TrancheReasonCode,
ai.ArrayItemDecode TrancheReasonDescription,
t.trancheuwstage as UnderwritingStatusCode
from plan_ p
inner join tranche t
on t.planno = p.planno
and t.trancheuwstage in ( 2, 4 )
and p.planno = '040000000X6'
inner join arrayitem ai
on ai.ArrayNm = 'arrTraReas'
and ai.ArrayItemCode = t.tranchereasoncode;
and the culprit here is tranchestartdate which is a DATETIME. I can't really add anything to tabel as i'm not allowed to change existing table structures, this is a big system. Perhaps i can do the casting in my SQL? I'm not quite sure if this is definitely a null problem.. Can one debug/watch through the ResultSet and check if any data was retrieved before i call getDate()?
[/EIDT]

If your application (or drivers) cannot handle null dates then the easiest thing might be to use ISNULL(field, <null replacement date>) and check for the null replacement date in code. This approach uses a magic number (date) to indicate null values, true. It's not pretty but it is quick and straightforward.

Can't you use coalesce for this?
http://msdn.microsoft.com/en-us/library/ms190349.aspx

Are you selecting the datetime from a field or constructing it dynamically in your SELECT? you may have to CAST the result.
See this article

Related

Criteria JPA - Call Postgres CAST function

I'm trying to call a Postgres function with Criteria but it's not working. I need to use the LIKE clause in a UUID field, so I need to convert into VARCHAR first.
The result I need:
SELECT * FROM my_table WHERE cast(uuid as varchar(36)) like '%1234%';
What I'm doing in Criteria:
final Path<UUID> uuidField = from.get("uuid");
var cast = cb.function("cast", String.class, uuidField, cb.literal("as varchar(36)"));
cb.like(cast, String.format("%%%s%%", stringValue));
The query which is being generated:
HQL: select generatedAlias0 from com.MyTable as generatedAlias0 where function('cast', generatedAlias0.uuid, 'as varchar(36)') like '%1234%' order by generatedAlias0.name asc
Error:
2022-08-08 18:38:48,549 WARN [io.ver.cor.imp.BlockedThreadChecker] (vertx-blocked-thread-checker) Thread Thread[vert.x-eventloop-thread-9,5,main] has been blocked for 2393 ms, time limit is 2000 ms: io.vertx.core.VertxException: Thread blocked
at antlr.ASTFactory.make(ASTFactory.java:342)
at antlr.ASTFactory.make(ASTFactory.java:352)
at org.hibernate.hql.internal.antlr.HqlBaseParser.jpaFunctionSyntax(HqlBaseParser.java:4633)
at org.hibernate.hql.internal.antlr.HqlBaseParser.primaryExpression(HqlBaseParser.java:1075)
The log is not so clear (I'm using Quarkus + Hibernate Reactive), but I suspect it crashed in database because the function('cast', generatedAlias0.uuid, 'as varchar(36)').
I think it should be something like: function('cast', generatedAlias0.uuid, as varchar(36)) (without quotes). But I don't know how to achieve this result to test my theory.
How can I call this CAST function?
After investigating some possible solutions (I'm avoiding to create custom database routines) I found something interesting in a answer from another question:
Currently JPA does not have APIs for replace() and cast(string as numeric). But you can use CriteriaBuilder.function(...) to create database native functions if database portability is not critical.
Source: JPA criteria builder: how to replace and cast a string to numeric in order-by?
I don't know if this is documented is some place, but assuming that there is no way to call CAST(x AS y) using Criteria, I tried a workaround to force the UUID to VARCHAR cast without using the probably unsupported CAST function.
I tested this direct SQL query to database:
SELECT * FROM my_table WHERE concat(uuid, '') like '%123%';
And it works. This CONCAT forces the cast to VARCHAR and the LIKE function does his job. Knowing this, I did:
final Path<UUID> uuidField = from.get("uuid");
var cast = cb.function("concat", String.class, uuidField, cb.literal(""));
cb.like(cast, String.format("%%%s%%", stringValue));
Worked perfectly. I hope this help someone else.
As #HaroldH said, it's a weird requirement, but happened in my project.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

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;

Query.setparameter using TemporalTipe.Time

I wanna do SELECT e FROM Pedidos e WHERE e.diaPedido = :diaPedido AND e.horaPedido = :horaPedido.
When I write parameters use query.setParameter("diaPedido", fechaEscogida, TemporalTipe.DATE) and query.setParameter("horaPedido", horaEscogida, TemporalTipe.TIME) but i don´t know why second filter Temporal.TIME doesn´t work because still compare like TIMESTAMP.
I use eclipseLink 2.3.0 and javax.persistence 2.0.1.
diaPedido and horaPedido are both Date in oracle database.
If you want to just compare the time portion of a TIMESTAMP column, you need to use a database function.
In EclipseLink (>=2.4) you can use EXTRACT or CAST, or the FUNCTION/FUNC operator to call a database function.
See,
http://java-persistence-performance.blogspot.com/2012/05/jpql-vs-sql-have-both-with-eclipselink.html

Hibernate Criteria for Time > 0

I am to fix an older project, in which there is a database query gone wrong. In the Table, there is a field
viewTime TIME NOT NULL DEFAULT 0
I need to filter out the rows that actually have 0 as their viewTime:
Criteria query = /* create criteria */;
query.add(Restrictions.gt("viewTime", 0));
However, since viewTime is defined as a Date:
#Temporal(TemporalType.TIME)
private Date viewTime;
I get a casting exception. On the other hand, I have no idea how to create a valid Date object that represents time 0. I can't change the type of the field as well for this.
Any way I can express viewTime > 0 in this Criteria object?
I think you have to compare date object with (00/00/00) but the any API will not produce DATE value like it.
This might your solution convert to null refer this link
It seems to me, that you can try such construction:
Criteria query = /* create criteria */;
query.add(Restrictions.gt("viewTime", new Date(0)));

Retrieving a max date from DB2 in Java throwing wrong column type conversion exception

I have the following SQL that returns the max BILL_DATE based on some criteria. BILL_DATE is defined in the database as a DATE.
SELECT MAX(BILL_DATE)
FROM BILLTABLE
WHERE col1 = ? and
col2 = ?
But when I read the value from the resultSet.
bill.setBillDate(resultSet.getDate(1));
An exception is thrown:
Invalid data conversion: Wrong result column type for requested conversion. ERRORCODE=-4461, SQLSTATE=42815
I have also tried
bill.setBillDate(resultSet.getString(1));
But that doesn't return a date. It returns either 100, 200 or 300 which is obviously not correct.
Is there another way to do this? Am I doing something wrong?
Ash is right, how are you defining the date column?
Is it possible the column is timestamp? In that case try resultSet.getTimestamp(1))
I had two resultSets open in the function where I was reading in the BILL_DATE. I changed the code to the following and it works fine.
bill.setBillDate(resultSet1.getDate(1));

Categories

Resources