JPA criteria API query for date Interval - java

How to write the java criteria query for hibernate3.
Select * from some_table where created_at between DATE_SUB(curdate() , INTERVAL 8 DAY) and date_sub(curdate() ,INTERVAL 2 DAY)
CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<MyEntity> criteria = builder.createQuery(MyEntity.class);
Root<MyEntity> root = criteria.from(MyEntity.class);

Using the old java.util.Calendar and java.util.Date.
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -8);
Date eightDaysAgo = now.getTime();
now.add(Calendar.DATE, 6);
Date twoDaysAgo = now.getTime();
Expression<Date> createdAt = root.<Date>get("created_at"); // choose the name of the property in Entity definition
Predicate predicate = builder.between(createdAt, twoDaysAgo, eightDaysAgo);
criteria.where(predicate);

Related

JPA Criteria add one day to the selected date

I have a JPA criteria that selects the max date from a table and I want to select the following day, e.g. if the query result is 1/20/17 I want the result to be 1/21/17
Here is my code:
CriteriaQuery<Date> maxDateCriteriaQuery = criteriaBuilder.createQuery(Date.class);
Root<DatesClass> datesClassRoot = maxDateCriteriaQuery.from(DatesClass.class);
maxDateCriteriaQuery.select(criteriaBuilder.greatest(datesClassRoot));
TypedQuery<Date> maxDateTypedQuery = entityManager.createQuery(amortizationsQuery);
Date maxDate = maxDateTypedQuery.getSingleResult();
I want to change the criteria to return the max date + 1
In oracle I will do it:
SELECT MAX(MY_DATE) + 1 FROM DATES_TABLE;
I will appreciate any help!
I assume you want to keep the original Date object in the database?
Than I would add 1 day to the day you retrieved from your DB:
Calendar c = Calendar.getInstance();
c.setTime(maxDate);
c.add(Calendar.DATE, 1);
Date newMaxDate = c.getTime();

query to check the timestamp

In my java project I want to list the values of a table
programtable.
There are four fields programid, programname, startdate and enddate in table.
I want to list the details of programs done in today.
The startdate and enddate are in database datatype as TIMESTAMP. Help me to find the query to get the details of programs done on today.
I add my code to this. I use this method. But its not work,
String todayDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
todayDatem=todayDate+" 00:00:00";
todayDaten=todayDate+" 23:59:59";
Timestamp timestamp1 = Timestamp.valueOf(todayDatem);
Timestamp timestamp2 = Timestamp.valueOf(todayDaten);
System.out.println("timestamp1:"+timestamp1+timestamp2);
String sql3 = "select * form programtable where startdate between '”+timestamp1+”' and '”+timestamp2+”'";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<programmodel> pgm = jdbcTemplate.query(sql3, ParameterizedBeanPropertyRowMapper.newInstance(programmodel .class));
It is better to use placeholders instead of text dates in the query:
java.sql.Date d1 = new java.sql.Date(System.currentTimeMillis());
java.sql.Date d2 = new java.sql.Date(System.currentTimeMillis() + 24 * 3600 * 1000);
String sql3 = "select * from programtable where startdate between ? and ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<programmodel> pgm = jdbcTemplate.query(sql3, ParameterizedBeanPropertyRowMapper.newInstance(programmodel.class), d1, d2);
If you mean started and finished today
SELECT *
FROM programtable
WHERE startdate = CURDATE() AND enddate = CURDATE();
If you mean started today
SELECT *
FROM programtable
WHERE startdate = CURDATE();
If you mean finished today
SELECT *
FROM programtable
WHERE enddate = CURDATE();

Criteria for getting month from date in hibernate3

I have stored the date in my database (not months).i want to get the records from particular month.Is it possible to write criteria for this in hibernate3?
You can write like this
Date startDate = 2014-03-01
Date endDate = 2014-03-31
Criteria criteria = getSession().createCriteria(getDomainClass());
criteria.add(Restrictions.between("date", startDate, endDate));
(OR)
If your date format is "YYYY-MM-DD"
String date = "2014-03";
Criteria criteria = getSession().createCriteria(getDomainClass());
criteria.add(Restrictions.like("date", date));

Hibernate Criteria: NOW() < date + 1 day

I have a table in a MySQL DB with a date(DATETIME) column on it. How do I express it in java Hibernate criteria if let's say I would like to query for records where NOW() < ('date' + 1 day) ?
You could turn it the other way around and compare 'date' >= (NOW - 1 day).
Assuming you've got a mapped MyTable class with the date property:
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
Criteria criteria = session.createCriteria(MyTable.class);
criteria.add(Restrictions.ge("date", c.getTime());
List results = criteria.list();

Hibernate Criteria for Dates

In oracle I have dates in format
17-April-2011 19:20:23.707000000
I would like to retrieve all orders for 17-04-2011.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
Criteria criteria =
session.createCriteria(Order.class);
Criterion restrictDate = Restrictions.like("orderDate",date);
but it brings me empty result:
Why do you use Restrictions.like(...)?
You should use Restrictions.eq(...).
Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column.
Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.
For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).
In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).
Your date object you got with the code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.
This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".
If you want to retrieve all entries of your database from a given day, you will have to use the following code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
// Create date 17-04-2011 - 00h00
Date minDate = formatter.parse(myDate);
// Create date 18-04-2011 - 00h00
// -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
Conjunction and = Restrictions.conjunction();
// The order date must be >= 17-04-2011 - 00h00
and.add( Restrictions.ge("orderDate", minDate) );
// And the order date must be < 18-04-2011 - 00h00
and.add( Restrictions.lt("orderDate", maxDate) );
By using this way you can get the list of selected records.
GregorianCalendar gregorianCalendar = new GregorianCalendar();
Criteria cri = session.createCriteria(ProjectActivities.class);
cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime()));
List list = cri.list();
All the Records will be generated into list which are greater than or equal to '08-Oct-2012' or else pass the date of user acceptance date at 2nd parameter of Restrictions (gregorianCalendar.getTime()) of criteria to get the records.
If the column is a timestamp you can do the following:
if(fromDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')"));
}
if(toDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')"));
}
resultDB = criteria.list();
try this,
String dateStr = "17-April-2011 19:20:23.707000000 ";
Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String newDate = format.format(dateForm);
Calendar today = Calendar.getInstance();
Date fromDate = format.parse(newDate);
today.setTime(fromDate);
today.add(Calendar.DAY_OF_YEAR, 1);
Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.add(Restrictions.ge("dateFieldName", fromDate));
crit.add(Restrictions.le("dateFieldName", toDate));
return crit.list();

Categories