Criteria for getting month from date in hibernate3 - java

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

Related

How to build a Spring Query in Mongo DB with a criteria considering two string date range

I have to build a criteria of a find query using a date field which is stored in String format.
The criteria I've written is like this:
Query findQuery = new Query()
findQuery.addCriteria(Criteria.where(mongoField).gt(startDate).lt(endDate));
where the "mongofield" is a String type, but "startDate" and "endDate" are a LocalDate type.
This criteria obviously doesn't work because the comparison is ineffective.
I've found that I should use $expr operator together with $dateFromString, but I didn't find any clear example of use in Java code.
Please, can anyone help me in writing a good statement in Spring Java code?
You can convert LocalDate to a string and then compare
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.now().plusDays(20);
// Define time format converter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Convert LocalDate type to String type
Criteria criteria = Criteria.where("mongoField").is("").gte(startDate.format(formatter)).lt(endDate.format(formatter));
Query query = new Query(criteria);

HQL query to select data between two dates not returning any record

ReportView
I'm getting values of Dates from JavaFX DatePicker objects tDateFrom, tDateTo.
I've tried,
(1)
List list = session.createQuery("from ReportView where date between :stDate and :edDate")
.setTimestamp("stDate", Date.from(Instant.from(tDateFrom.getValue().atStartOfDay(ZoneId.systemDefault()))))
.setTimestamp("edDate", Date.from(Instant.from(tDateTo.getValue().atStartOfDay(ZoneId.systemDefault()))))
.list();
(2)
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date frmDate = format.parse(tDateFrom.getValue().toString());
Date enDate = format.parse(tDateTo.getValue().toString());
list = session.createQuery("from ReportView where date between :stDate and :edDate")
.setTimestamp("stDate", frmDate)
.setTimestamp("edDate", enDate)
.list();
Both methods are not returning any row.
java.text.ParseException: Unparseable date: "2020-02-03"
at java.text.DateFormat.parse(DateFormat.java:366)
I've tried to fire query as mentioned in answer of this question : mysql select query where date = ... not returning data
But this query works in mySQL, not in HQL. How to use between clause for dates in HQL?

Sqlite : Comparing timestamp value stored in a column to current Date

I store information in a sqlite database table as follows:
ActionDate column is of type : DEFAULT CURRENT_TIMESTAMP
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I want to write an SQL query that returns all rows in my table having ActionDate value as today's date from sqlite DB. However as ActionDate is of type timestamp what is the most appropriate way to convert it to todays date.
If you want current date then use the following query :
SELECT date('now');
To get all columns in your table having ActionDate equal to todays date use the below query :
select * from table where strftime('%Y-%m-%d ', datetime(ActionDate, 'unixepoch')) = date('now)' ;
more info on SQLite Date & Time queries can be found here

Criteria query for fetching the data after particular date and time

I am using the criteria query as follows:I want to fetch the reservations after the time and date I have passed.but now i am getting the reservation before the time which i have passed for the same date.Please help..
#GET
#Path("/getReservationByUserIdAndTypeAndDateTime/{userid}/{type}/{date}/{time}")
public List<Reservation> getReservationByAndUserIdAndTypeAndDateTime(#PathParam("userid") int uid, #PathParam("type") int tid,#PathParam("date") Date date,#PathParam("time") Time time) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Reservation> criteria = builder.createQuery(Reservation.class);
Root<Reservation> r = criteria.from(Reservation.class);
TypedQuery<Reservation> query = em.createQuery(
criteria.select(r).where(new Predicate[]{
builder.equal(r.get(Reservation_.usersId), uid),
builder.equal(r.get(Reservation_.reservationsType), tid),
builder.greaterThanOrEqualTo(builder.concat(r.get(Reservation_.date), " "+r.get(Reservation_.time)), date.toString()+" "+time.toString())}));
return query.getResultList();
}
Comparing dates and times formatted as string is not advisable, results can depend on the format. It would be better having a unique Date field in the Reservation class:
#Temporal(TIMESTAMP) Date date;
and using date comparison in the query:
builder.greaterThanOrEqualTo(r.get(Reservation_.date), date)
This way the time parameter in the getReservationByAndUserIdAndTypeAndDateTime method can be omitted, since the date parameter would hold both date and time.

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