I need to write a query to get an object between a range of time, currently the query looks like this:
Timestamp from = ...
Timestamp to = ...
getHibernateTemplate().find("from " + Person.class.getName() + " ml where ml.lastModifiedOn>="+from.toString()+" and m1.lastModifiedOn<=" + to.toString());
However, this doesnot work for obvious reasons. How can I format the timestamp to be acceptable by the query.
org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: 16 near line 1, column 123 [from Person ml where ml.lastModifiedOn>=2010-02-12 16:00:21.292 and m1.lastModifiedOn
You're missing single quotes in your current query. The following should work:
from Person ml where ml.lastModifiedOn
between '2010-02-12 16:00:21.292' and '2010-02-12 23:00:21.292'
Note that I don't know why you're not passing Date instances to the following query:
from Person ml where ml.lastModifiedOn between :from and :to
Are you using java.sql.Timestamp here? If yes, you shouldn't.
You can simply pass a long (from.getTime()) in the comparison, if it is represented as long in the DB.
Otherwise you can use these functiomns: second(...), minute(...), hour(...), day(...), month(...), and year(...)
How about something like this?
String sql = "from " + Person.class.getName() + " ml where ml.lastModifiedOn>= ? and m1.lastModifiedOn<= ?";
Date from = ...;
Date to = ...;
getHibernateTemplate().find(sql, new Object[] {from,to});
If you want to query for something between you can do the following:
public List findPerson() {
Date from = ...;
Date to = ...;
return entityManager.createQuery(
"SELECT p from Person p WHERE p.lastModifiedOn BETWEEN ?1 AND ?2")
.setParameter(1,from, TemporalType.DATE)
.setParameter(2,to, TemporalType.DATE).getResultList();
}
You might need to change TemporalType.DATE to whatever you are using
Related
I did a SQL query in Java as follows:
"SELECT A.ID_MACHINE, A.HEURODATAGE, A.COMPTEUR, B.LIBELLE_IDMACHINE, C.LIBELLE_STATUT, C.CODE_COULEUR FROM ROXJAVA.MACH0004 A " +
"JOIN ROXJAVA.MACH0003 B ON A.ID_MACHINE = B.ID_MACHINE " +
"JOIN ROXJAVA.MACH0002 C ON B.CODE_MACHINE = C.CODE_MACHINE " +
"WHERE A.ID_MACHINE = ? AND A.HEURODATAGE BETWEEN '?' AND '?' AND A.CODE_STATUT = C.CODE_STATUT AND C.CODE_COULEUR = ? " +
"ORDER BY A.HEURODATAGE DESC";
In my WHERE it finds "Heurodatage" which must contain a time and a date with this format:
'2018-07-03 09:30:00.000'
I then want to retrieve the results of this query with the help of a method that takes into account the different attributes that I need to replace the? in my request.
But now I can not determine the type of my dates.
I'm getting "type not match" when I try to run with a String.
If the column is a date column, you want to pass in a date type:
PreparedStatement ps = ...;
ps.setDate(N, java.sql.Date.valueOf(your_date_value));
where it would be best if your_date_value is a java.time.LocalDate, but could also be parsed from a String (in a valid format).
I have a Java EE application that has a named Query in an entity called download.
The named query is:
#NamedQuery(name="Users.DownloadCount",
query="SELECT u.fullName, count(u.downloads) FROM WebUser u "
+ "JOIN u.downloads ud WHERE ud.downloadTime "
+ "> :startDate AND ud.downloadTime < :endDate")
I attempt to do the following query in one of my methods:
List<Object[]> downloads = new ArrayList();
if(userName==null){
downloads = manager.createNamedQuery("Users.DownloadCount").setParameter("startDate", sDate,TemporalType.DATE)
.setParameter("endDate", eDate,TemporalType.DATE).getResultList();
The date variables sDate and eDate are:
Date sDate = format.parse(startDate);
Date eDate = format.parse(endDate);
For some reason however I seem to be getting a :
java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
exception.
I have pulled the query out of the entity class and done a normal entitymanager query call but I still get the same exception.
Add a blank between ud.downloadTime and > :s and between ud.downloadTime and < !
I realised the problem:
First problem: Missing a group by with the aggregate function
Second problem: Not joining the entities WebUser and Downloads so no way for the function to count the amount of related entities.
Query should be:
"SELECT u.fullName, count(d) FROM WebUser u JOIN u.downloads d "
+ "WHERE d.downloadTime > :startDate AND d.downloadTime< :endDate"
+ " GROUP BY u.fullName"
I have a variable type time in a column of a table of the database.
How can I compare this value in java with this field I mean can i use date, gregoriancalendar?
I've tried adn I still have this message, please can someone give me an advice
Date d2 = new Date(); // timestamp now
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(d2); // set cal to date
cal.set(Calendar.HOUR_OF_DAY, 10); // set hour to midnight
cal.set(Calendar.MINUTE, 30); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millis in second
Date d3 = cal.getTime();
#SuppressWarnings("unchecked")
List<Asistencia> list = (List<Asistencia>) sessionFactory
.getCurrentSession()
.createQuery(
"select new Asistencia( asis.idAsistencia,"
+ "asis.horaInicio, asis.horaFin) "
+ "from Asistencia asis "
+ "where :hour >= asis.horaInicio and :hour <= asis.horaFin")
.setParameter("hour", d3).list();
I also used between
where :hour between asis.horaInicio and asis.horaFin
and the mesage is the same:
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - The data types datetime and time are incompatible in the greater than or equal to operator.
The data types datetime and time are incompatible in the greater than or equal to operator.
Here the class Asistencia:
public class Asistencia implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long idAsistencia;
private Date horaInicio;
private Date horaFin;
private int idAula;
private int idCurso;
private int idPeriodo;
private Date fecha;
public Asistencia (){
}
public Asistencia (long idAsistencia, Date horaInicio, Date horaFin){
this.idAsistencia
this.horaInicio = horaInicio;
this.horaFin = horaFin;
}
}
It seems the only problem was I'm using SQL Server 2008 and is necessary to put sendTimeAsDateTime=false in the connections properties.
Here a similar question.
comparing time in sql server through hibernate
I encountered this error using SpringBoot(v2.2.2) and MSSQL server (jdbc7.4.1) when calling a JpaRepository API passing null dates. This was first version Repository API
#Query(value = "SELECT t FROM MyEntity t WHERE "
+ " AND ( ?3 IS NULL OR ( ?3 IS NOT NULL AND t.fromDate<= ?3 ))"
+ " AND ( ?2 IS NULL OR ( ?2 IS NOT NULL AND t.toDate>= ?2 ))")
List<MyEntity> getMyEntity(LocalDate fromDate, LocalDate toDate);
When calling API with null value for input dates i got the exception:
The data types date and varbinary are incompatible in the less than or equal to operator
I solved with a CAST:
#Query(value = "SELECT t FROM MyEntity t WHERE "
+ " AND ( ?3 IS NULL OR ( ?3 IS NOT NULL AND t.fromDate<= CAST( ?3 AS date ) ))"
+ " AND ( ?2 IS NULL OR ( ?2 IS NOT NULL AND t.toDate>= CAST( ?2 AS date ) ))")
List<MyEntity> getMyEntity(LocalDate fromDate, LocalDate toDate);
Without setting that sendTimeAsDateTime property, which is not available for the SQL Server drivers older than 3.0 (and some of us are stuck with what we have, for reasons), you could try to use a String instead of a date. This worked for me using a PreparedStatement and I bet it would work in this scenario also. Change the last line of your first code block to:
.setParameter( "hour", new SimpleDateFormat("HH:mm:ss.SSS").format(d3) ).list();
I've encountered the same issue when querying data by entity property of type javax.time.LocalDate via spring-data-jpa and eclipselink . Connection setting sendTimeAsDateTime=false didn't help. This was fixed by adding spring-data-jpa converter <class>org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters$LocalDateConverter</class> into the persistence.xml file. Hope this helps.
I also have the same issue. My sql data type is Time(7) and each time I want to compare it via JPQL query, that error comes out. Connection string sendTimeAsDateTime=false didn't work. Adding <class>org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters$LocalDateConverter</class> into the persistence.xml also didn't work.
What I do is, store data Time(7) from sql into String, for example this is my table design on sql
StartTime time(7)
In my java class I store that field into String variable
#Entity
#Table(name = "tableSchedule")
public class TableSchedulue implements Serializable {
private static final long serialVersionUID = -9112498278775770919L;
....
#Column(name = "StartTime")
private String startTime;
.....
}
When I use JPQL query like this (in repository)
#Query(value = "SELECT a "
+ "FROM TableSchedule a "
+ "WHERE a.startTime <= ?1 ")
List<TableSchedulue > getTestData(String startTime);
Your string format must HH:mm:ss
It works. Hope it helps
CONS : Because in SQL the type is Time(7) so value 08:00:00 in SQL will become 08:00:00.0000000 in persistence so you need to parse it into your needs
I would like to parse an input date in java, and then use it in a query as a condition in a select in oracle database.
String date = "2013.11.05";
Date checkDate = new SimpleDateFormat("yyyy.MM.dd").parse(date);
String qString =
"SELECT DISTINCT T " +
"FROM T5PFArfolyamArch T " +
"WHERE T.arfTipus = :vcRateKod AND T.arfErvkezd = :checkDate AND T.araValid IN ('I','M')";
Query query = entityManager.createQuery(qString);
query.setParameter("vcRateKod", tipus);
query.setParameter("checkDate", checkDate);
But it gives 0 result, like the date is not equal or right format to select anything.
try this
query.setParameter("checkDate", checkDate, TemporalType.DATE);
I have....
string qString = "select e from table where id= :id and trunc(Date) = TO_Date('03/04/2010','MM/DD/YYYY')
Query newQuery = entityManager.createNamedQuery(qstring)
newQuery.setParameter("id",id);
How do I set the date part rather than hard coding it?
I have tried
newQuery.setParameter("date",date,TemporalType.Date) but it hasn't worked for me. Any pointers?
I have also tried to use just 'newQuery.setParameter("date",date)' and used date as an argument ending me with...
string qString = "select e from table where id= :id and trunc(Date) = :date
, but I believe they aren't formatted correctly, what is the correct way to do this?
*UPDATE*** I am trying to do it with SQL date. Will keep you posted!!!
What is wrong with storing them in Strings just like you do the query??
String date = '03/04/2010';
String dateFormat = 'MM/DD/YYYY';
String qString = "SELECT e FROM table WHERE id = :id
AND trunc(DATE) = TO_Date(date,dateFormat)";