How to write a JPA query to find objects between two dates? - java

Here's my query
#Query(value = " SELECT * FROM account.statement where `date` between ?1 and ?2")
List<Statement> findAllByDate(String startDate, String endDate);
And this is the error message I get
Caused by: org.hibernate.QueryException: unexpected char: '`' [ SELECT * FROM account.statement where `date` between ?1 and ?2]
The date is the column name. I want to retrieve a list of Statement objects between two dates. The dates in this case are LocalDate objects, like 2000-10-10. I tried using String and a LocalDate type in the parameters, still doesn't work.
I've searched everywhere, on stack overflow and baeldung. I am stuck

List<Statement> findByDateBetween(Date start, Date end);

Turns out this was the correct implementation
#Query(value = "SELECT * FROM account.statement WHERE date > ?1 AND date <= ?2",
nativeQuery = true)
List<Statement> findAllByDate(LocalDate startDate, LocalDate endDate);
Thank you my guy Thomas

You should be binding LocalDate, not String, to the placeholders:
#Query(value = " SELECT * FROM account.statement WHERE date BETWEEN ?1 and ?2")
List<Statement> findAllByDate(LocalDate startDate, LocalDate endDate);

#Query("select a from Statement a where a.startDate >= :startDate and a.endDate <= :enddate")
List<Statement> findAllByDate(
#Param("startDate") Date startDate,#Param("endDate") Date endDate);

while using #Query might solve the problem, but you can also use JpaRepository in this case
First of all you need to add JpaRepository to your repository
interface :
extends JpaRepository<Statement, Long>
use this line and replcae Date with the date column name and use the appropriate type of date:
List findByDateBetween(LocalDateTime to, LocalDateTime
from);
exemple :
#Repository
public interface StatementRepository extends JpaRepository<Statement, Long> {
//where x.startDate between ?1 and ?2
List<Statement> findByDateBetween(LocalDate to,LocalDate from);
}
for more information you can see the doc

Related

Hibernate method name to SQL query - OR statement

My entity has 2 dates - startingDate, buildingDate.
I need a query that finds all rows with either date between 2 parameter dates.
public List<Factory> findByStartingDateBetweenOrBuildingDateBetween(LocalDate from, Localdate to);
Writing such method gives me an error and I have to extend parameters by another 2 dates.
public List<Factory> findByStartingDateBetweenOrBuildingDateBetween(LocalDate from, Localdate to, LocalDate fromDate, LocalDate toDate);
Is there a way to write such method that only takes 2 parameters and assigns them to both dates in the query?
I hope the below method will works for you.
public List<Factory> findAllByStartingDateLessThanEqualAndBuildingDateGreaterThanEqual(LocalDate startingDate, LocalDate buildingDate);
Use below native query above the method, Hope this will works for you.
select * from factory where (starting_date>=:from and starting_date<=:to) or (building_date>=:from and building_date<=:to);
SELECT * FROM Table_name WHERE start_date >=:from AND start_date<=:to
by using this query you can get the list of data in between this date
try this-
native query method -
#Query(value = "select * from factory where (starting_date>= ?1 AND starting_date<= ?2) OR (building_date>= ?1 and building_date<= ?2)", nativeQuery = true)
List<Factory> findFactoryByDate(LocalDate from, Localdate to);
JPA QUERY METHOD
public List<Factory> findByStartingDateOrBuildingDateBetween(LocalDate from, Localdate to);
Set<Factory> findAllByStartingDateBetween(Date Start, Date End);

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

Using joda DateTime in parameters for native query in spring-data-jpa fails because of bad binding

Here are two queries that should be exactly the same except one is marked as native and the other is not. The first one works fine, but the second one fails with incompatible data type in conversion
#Transactional(readOnly = true)
#Query(value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
List<DateTime> findStartDateByStartDateBetween(#Param("startDate") DateTime startDate,
#Param("endDate") DateTime endDate);
This generates the query:
select taskmetric0_.startDate as col_0_0_ from TaskMetrics taskmetric0_ where taskmetric0_.startDate between ? and ?
With bindings
binding parameter [1] as [TIMESTAMP] - [2015-02-02 10:57:14.279]
binding parameter [2] as [TIMESTAMP] - [2015-02-04 10:57:14.281]
-
#Transactional(readOnly = true)
#Query(nativeQuery = true, value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
List<DateTime> findStartDateBetween(#Param("startDate") DateTime startDate,
#Param("endDate") DateTime endDate);
This generates the query:
select startDate from TaskMetrics where startDate between ? and ?
With one binding, which also seems a bit odd (especially why #2?):
binding parameter [2] as [VARBINARY] - [2015-02-04T10:57:14.315-05:00]
I'm using Hibernate 4.3.8.Final as my JPA 2.1 provider and Jadira Usertype 3.1.0.CR10 for JodaTime support.
Am I doing something wrong or is this a bug somewhere?
Bug opened here - https://jira.spring.io/browse/DATAJPA-671
Workaround for the bug:
public class MyDaoClass {
// Converter provided by joda time user type library
private TimestampColumnDateTimeMapper columnDateTimeMapper = new TimestampColumnDateTimeMapper();
#Override
public void doAction(MyObject myObject) {
Query q = getEntityManager().createNamedQuery("MyNativeNamedQuery");
q.setParameter("date", columnDateTimeMapper.toNonNullValue(myObject.getDate()), TemporalType.TIMESTAMP);
q.executeUpdate(); // or select
}
The second one is a nativeQuery as i know the will not work with joda DateTime. use Java.sql.Date instead.

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

Categories

Resources