Search This Blog

How to compare two string dates in hibernate using criteria if DB field

 
It is very simple and easy to do in hibernate using criteria condition. Let's say we have two fields like from date and to date As "String". 

First we should consider below mentioned conditions while developing it

It will be like below cases: 
  1. User select fromdate and didnt select todate than 'it should fetch all records from fromdate to systemdat'
  2. if user select only todate and not formdate than it should fetch all record till todate
  3. If user enter both than it should filter the record in date range and display
  4. If fromdate > todate then we should through error 
  5. Both are not given than it should find all the records till Systemdate i.e. Today
Code will be look like something as :
 Hibernate DAO layer:
if(!Utils.isNullOrEmpty(model.getDateFrom()) && !Utils.isNullOrEmpty(model.getDateTo())) { cr.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + model.getDateFrom() + "','dd/mm/yyyy')"));
 cr.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + model.getDateTo() + "','dd/mm/yyyy')"));
 }
 else if(!Utils.isNullOrEmpty(model.getDateFrom()) && Utils.isNullOrEmpty(model.getDateTo())) {
 cr.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + model.getDateFrom() + "','dd/mm/yyyy')"));
 //cr.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + Utils.formatNewDate() + "','dd/mm/yyyy')"));
 }
 else if(Utils.isNullOrEmpty(model.getDateFrom()) && !Utils.isNullOrEmpty(model.getDateTo())) {
 cr.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + model.getDateTo() + "','dd/mm/yyyy')"));
 }
Utils.java:
public class Utils {
 public static Boolean isNullOrEmpty(String str){
 return (str != null && !str.isEmpty()) ? false: true;
 }
}

No comments:

Post a Comment

Are You A Thinker Or Maybe It's Overflowing?

Hi, everybody. I'm Rohit Patel and I'd like to ask you today, "Are you a thinker Or maybe it's overflowing? Do you live in ...

Popular Posts