I'm facing a strange issue. I've search including here in stack overflow and for JPA and Custom query I should specified the parameter. So I have a query string since I have over 14 fields but I'm facing issues with the dates. I'm always getting the IllegalStateException
INFO: query STRING = SELECT t FROM Tickets t WHERE t.startdate > :startDate AND t.enddate < :endDate ORDER BY t.status DESC
WARNING: #{ticketController.search}: java.lang.IllegalStateException: Query argument startDate not found in the list of parameters provided during query execution.
as for my query:
Query q = em.createQuery(query).setParameter("startDate", startDate, TemporalType.TIMESTAMP).setParameter("endDate", endDate, TemporalType.DATE);
Although I'm getting that the parameter is not found, I have it in the setParameter and also set in the query as seen in the INFO line.
Any ideas?
Thanks in advance
EDIT:
INFO: query STRING = SELECT t FROM Tickets t WHERE t.startdate > ?1 AND t.enddate < ?2 ORDER BY t.status DESC
WARNING: #{ticketController.search}: java.lang.IllegalStateException: Query argument 1 not found in the list of parameters provided during query execution.
q = em.createQuery(query).setParameter(1, startDate, TemporalType.TIMESTAMP).setParameter(2, endDate, TemporalType.TIMESTAMP);
Also and as advised, I've checked that the Date I'm using is java.util.Date. and in the entity class I have as Timestamp. But still I cannot have this working and not sure where I am failing.
Just to make sure that all the things are as they should, I forced the query to be string and I got the correct Exception:
INFO: query STRING = SELECT t FROM Tickets t WHERE t.startdate > :startDate AND t.enddate < :endDate ORDER BY t.status DESC
WARNING: #{ticketController.search}: java.lang.IllegalArgumentException: You have attempted to set a value of type class java.lang.String for parameter startDate with expected type of class java.util.Date
But then again, I change to date and it fails :S
I've checked the reasons for this IllegalStateException:
And from the debug and from the javadoc I get the following:
getResultList
IllegalStateException - if called for a Java Persistence query language UPDATE or DELETE statement.
I'm not doing a update nor delete :/
EDIT 2: Adding the Entity relevant part:
#Basic(optional = false)
#NotNull
#Column(name = "startdate")
#Temporal(TemporalType.TIMESTAMP)
private Date startdate;
#Column(name = "enddate")
#Temporal(TemporalType.TIMESTAMP)
private Date enddate;
AS for the database creating script the columns are being created like this:
startdate timestamp with time zone NOT NULL,
endate timestamp with time zone,
If I do a normal SQL query like:
"select * from tbl_tickets where startdate > '2012-02-01 00:00:00' and enddate < '2013-03-18 23:59:50'"
I get the desired results. I guess I could do with native query but that would be going around the problem and not fixing this issue, right?
EDIT 3: Although I had everything set up properly, the init of the bean was calling again the query without the args ( sorry and thank you all for your help. It helped me checking what was amiss)
javadoc for both
setParameter(String name, java.util.Date value, TemporalType temporalType)`
setParameter(String name, java.util.Calendar value, TemporalType temporalType)`
states:
Throws: IllegalArgumentException - if the parameter name does not correspond to a parameter of the query or if the value argument is of incorrect type
Since you didn't provide full code, verify that:
Java value startDate is of type java.util.Date or java.util.Calendar.
SQL column startDate has valid SQL date type TIMESTAMP.
I think that there should be a space between :(colon) and startDate in between. May be it is considering :startDate as a single word. Try this once
Try
String query = "SELECT t FROM Tickets t WHERE t.startdate > ?1 AND t.enddate < ?2 ORDER BY t.status DESC";
Query q = em.createQuery(query).setParameter(1, startDate, TemporalType.TIMESTAMP).setParameter(2, endDate, TemporalType.DATE);
Query q = em.createQuery(query).setParameter("startDate", startDate, TemporalType.TIMESTAMP).setParameter("endDate", endDate, TemporalType.DATE);
If you carefully look at the setParameter you're using, it says that this setParameter requires a Positional Parameter, whereas, seeing your query, it seems you've used Named Parameter.
Hence, the IllegalStateException. Either change your query to provide Positional Parameters, or the setParameter to provide Named Parameters as input.
This is how you provide Positional Parameter in the query.
String query = "SELECT t FROM Tickets t WHERE t.startdate > ?1 AND t.enddate < ?2 ORDER BY t.status DESC";
....
Query q = em.createQuery(query).setParameter(1, startDate, TemporalType.TIMESTAMP).setParameter(2, endDate, TemporalType.DATE);
Related
I have a mysql table called sp_500. Each record has a unique date. I want the last record in the table. It will have the max date. What is the best query to pull it? I tried the following HQL:
public interface QuoteRepository extends JpaRepository<Quote, Long> {
#Query("from sp_500 a where a.date in (select max(b.date) from sp_500 b)")
Quote getQuote(String symbol);
}
but when I run it, the following error is displayed:
Caused by: java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: sp_500 is not
mapped [from sp_500 a where a.date in (select max(b.date) from sp_500
b)]
Suggestions?
Can be done in two ways using the ORDER BY
1)
*Best practice
You can SELECT TOP 1 with the ORDER BY date desc.
Removing the MAX part of you QUERY
//If you are using ORACLE i think is ROW COUNT = 1
2)
You can make the SELECT * ... ORDER BY date desc
and just grab the first register
Thanks to #Nick and #luisfa19. You gave me valuable clues. Here is what worked:
#Query(value="select * from sp_500 order by date desc limit 1", nativeQuery = true)
I need help to write the JPA query (or function) to remove timestamps in search queries.
I am using MySQL DB.
My table consist of create_date(datetime) column.
My entity mapped with create_date using LocalDateTime
#Column(name = "create_date")
private LocalDateTime createDate;
I can achieve using the Mysql query in two ways.
select * from table_name where DATE(create_date) between '2019-07-01' and '2019-07-31'
select * from table_name where create_date between '2019-07-01 00:00:00' and '2019-07-31 23:59:59'.
I can achieve results using JPA also bypassing timestamp like
"where createDate between '2019-07-01 00:00:00' and '2019-07-31 23:59:59'"
Is there a way to build a query without passing time?
Something similar to Mysql query No.1
OHHHHHH I found an answer.
where DATE(createDate) between '2019-07-01' and '2019-07-31' is working.
I want to retrieve one of my column date in "mm/dd/yyyy" format. This column is currently returning date and time both but i want only date in "mm/dd/yyy" format.
Below is my postgresql query that i want to convert to criteria api
select DISTINCT c.name as Facility,
to_char(begin_exam,'mm/dd/yyyy') as begin_exam
from a inner join b on a.rad_exam_id = b.id
inner join c on c.id = b.site_id
group by c.name,to_char(begin_exam,'mm/dd/yyyy')
order by c.name,to_char(begin_exam,'mm/dd/yyyy')
I searched on the internet a lot but did't find any solution that will help me. please help me in writing criteria api query for this.
Criteria API defines function expression to execute native SQL functions in the CriteriaBuilder interface as follows:
<T> Expression<T> function(String name, Class<T> type, Expression<?>... args);
where name is the name of the SQL function, type is the expected return type and args is a variable list of arguments (if any).
Here is an example how to use it in a Criteria query:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(String.class);
Root<RadExamTimes> root = cq.from(RadExamTimes.class);
cq.select( cb.function("to_char", String.class, root.get("begin_exam"), cb.literal("MM/DD/YYYY")));
TypedQuery<String> query = entityManager.createQuery(cq);
List<String> result = query.getResultList();
where
RadExamTimes: a hypothetical root entity
MM/DD/YYYY: a database-specific format (in this example
Postgresql date format; for Oracle use Ora format, etc)
to_char: Postgresql function to convert date value to string
begin_exam: the date field to be formatted
The format string cannot be passed as is so that the literal() method is used to wrap it.
Note: The above example is tested on MySQL database with MySQL function and corresponding date format; but the example changed to match Postgresql syntax.
SELECT '2001-02-16 20:38:40'::date;
date
----------------
2001-02-16
(1 row)
Or you can use #TemporalType on JPA entity field.
If you want to display the column date in "mm/dd/yyyy" format for the sake of displaying it in the front end. Following might work on this case.
public class SomeDTO {
#JsonFormat(pattern="mm/dd/yyyy")
private Date someDate;
}
Assuming everything else works like a charm (entities, named queries, native named queries) I'm facing weird exceptions while trying to run following query, where date column type is TIMESTAMP:
#NamedNativeQuery(name = "problematicQuery", query = "DELETE FROM mytable WHERE date < ?")
I'm trying to execute this query using following code, where date is java.sql.Timestamp:
Query deleteQuery = em.createNativeQuery("problematicQuery");
deleteQuery.setParameter(1, date);
deleteQuery.executeUpdate();
This code results in following exception:
org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1
When I change the middle code line to this:
Query deleteQuery = em.createNativeQuery("problematicQuery");
deleteQuery.setParameter(0, date);
deleteQuery.executeUpdate();
I'll get the same exception with different position:
org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 0
I'm using JBoss 7.2.0.Final (Hibernate version is 4.2.0.CR1), Oracle 11g.
WHAT IS WRONG ? Am I missing something ?
Looks like you use wrong way
em.createNamedQuery("problematicQuery")
rather than
em.createNativeQuery("problematicQuery");
In your case a query created from string "problematicQuery" where no parameters exist
You should use named parameters inside JPA QL: #NamedNativeQuery(name = "problematicQuery", query = "DELETE FROM mytable WHERE date < :dt"
and deleteQuery.setParameter("dt", date);
I have an entity with a date field (java.util.Date). Normally the date is saved as for example 2012-10-19 21:29:03.000. My database is MySQL.
Now I need to query the database, through JPQL, using strictly the date portion, i.e., 2012-10-19. How would I do that?
That can be done by giving TemporalType when setting parameter:
Date param ...
Query q = em.createQuery("SELECT a FROM EntityA a WHERE a.someDate > :param");
q.setParameter("param", param, TemporalType.DATE);