Java persistence date query - java

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)";

Related

JPA Query for fomat Date

In Data base , createdDt is storing formated like:
15-01-20 10:43:20.394000000 AM
I am passing "created" as dd-mm-yyyy
I want to take the matching date from the table(without comparing time)
#Query("SELECT p FROM ABC p WHERE ( COALESCE(:created) is null or p.createdDt = :created) order by p.createdDt desc")
List<ABC> filterABC(#Param("created") Date created);
How to parse the date within query ?
You could try to use native query using specific DBMS stuff to extract date part.
#Query(value = "SELECT * from ABC where DATE_FORMAT(createdDt, '%d-%m-%Y') = ?1", nativeQuery = true)
List<ABC> filterABC(Date created);
DATE_FORMAT is MySQL specific function. Use the appropriate date function in accordance with your DBMS

Hibernate - filter Single Column data using date where clause

Lets say One table ABC having two column i.e. ID & CREATED_DATE
I want to fetch those ID which is created lets say '09-11-2017' and '09-17-2017'
Below SQL query working fine but I want to implement same logic using hibernate.
select ID from ABC where between TO_DATE('09-11-2017', 'MM-DD-YYYY') AND TO_DATE('09-17-2017', 'MM-DD-YYYY')
My code is not working.
public List getData(final Date startDate, final Date endDate){
String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
SQLQuery query = getSession().createSQLQuery(sqlString);
query.setParameter(CREATED_DATE);
return query.list();
}
You are missing End date parameter :
query.setParameter(CREATED_DATE, startDate);
query.setParameter(END_DATE, endDate);
It not work because you don't set the correct parameters :
String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
SQLQuery query = getSession().createSQLQuery(sqlString);
query.setParameter("startDate ", start_date);
query.setParameter("endDate", end_date);
return query.list();
The parameters must match the string on the query
Try this:
public List getData(final Date startDate, final Date endDate){
String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
SQLQuery query = getSession().createSQLQuery(sqlString);
query.setParameter("startDate",startDate);
query.setParameter("endDate",endDate);
return query.list();
}
--
pscar13

The data types datetime and time are incompatible in the greater than or equal to operator

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

Parse Date to compare in JPQL query

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);

HQL(hibernate) timestamp range match

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

Categories

Resources