I have some objects in db. Every object has parameter Date in date format like a "Mon Oct 05 08:55:36 CEST 2015". I want load all objects from 24h before to present time. I am using hibernate entity manager. Can you help me please
Here is my entity params:
private Long id;
private String email;
private String answer1;
private String answer2;
private Date date;
Here is table schema:
ID ; email ; answer1 ; answer2 ; date
1 ; any@thing.com ; 1234 ; 4321 ; 2015-10-04 18:01:19
I assume then, that the type of the date
table column is indeed SQL DATE
. In that case, you can simply run a HQL/JPQL query
SELECT e FROM YourEntity e WHERE e.date BETWEEN :from AND :to
Make a PreparedStatement out of it and provide the desired values for the from
and to
parameters. Sample using JPA:
EntityManager em = ...;
Date to = new Date();
Calendar fromCalendar = Calendar.getInstance();
fromCalendar.setTime(to);
fromCalendar.add(Calendar.HOUR_OF_DAY, -24);
Date from = fromCalendar.getTime();
em
.createQuery("SELECT e FROM YourEntity e WHERE e.date BETWEEN :from AND :to", YourEntity.class)
.setParameter("from", from, TemporalType.TIMESTAMP)
.setParameter("to", to, TemporalType.TIMESTAMP)
.getResultList();
Using JodaTime or Java8 Time package may make the whole date manipulation easier (didn't know if you were using those, so I gave an example using the "basic" Java classes).