JPA Criteria add one day to the selected date - java

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

Related

Inserting date 1 year from now into mysql Date column

I have a column in mysql table of type Date called expiryDate.
I want to get the date one year from now, and insert this into the expiryDate column.
I get the date 1 year from now:
import org.joda.time.LocalDate;
// expires 1 year fron now
LocalDate localDate = LocalDate.now();
LocalDate yearLater = localDate.plusYears ( 1 );
I get the error when I try to insert:
Incorrect date value: '\xAC\xED\x00\x05sr\x00\x17org.joda.time.LocalDate\xFF\xFF\xF8\x04\xD3\xE4\xEB\xB5\x02\x00\x02J\x00\x0CiLocalMillisL\x00\x0BiChro' for column 'expiryDate'
arguments:{ positional:{}, named:{expiryDate:2019-02-01,balance:50,orderId:761...
What am I doing wrong?
In MySQL, you could use DATE_ADD with INTERVAL 1 YEAR
SELECT NOW(), DATE_ADD(NOW(),INTERVAL 1 YEAR);
>>Demo<<
Using Java 8 :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
It will have no issue with MySQL driver.

compare existing month and year only in database after chosing date in java date picker

After chosing the date in date picker in java,i've got this format dd/mm/yyyy.But before inserting it in Oracle database i want first to compare only if month and year exist,not the day.If the month and year is already recorded i don't insert, if not,i insert it and reset the only the day to the first day of the month,but keep the month and year as they are.My program is only concerned by date and month,that why i want to know how to compare only the two before inserting.I've tried to do the following code:
Resultset res = st.executeQuery("select count(*) as rowCont from doc_arriv where month_arv=to_char(chosen_date,'mm/YYYY');
res.next();
But it isn't comparing
calendar=java.util.Calendar.getInstance();
calendar.setTime(chosen_date);
//we must add 1 here beacause Calendar intialise months by zero
int month= calendar.get(Calendar.MONTH)+1;
//we get the year
int year= calendar.get(Calendar.YEAR);
String req = "SELECT count(*) from doc_arriv where
EXTRACT(month FROM month_arv) = " + month +
"and EXTRACT(year FROM month_arv)= " = year ;
Resultset res=st.executeQuery(req);
res.next();
//continue your code here you must calculate the result of the request if more than 1 you insert else you dont insert and for change the day to the first day of month you must execute the code
calendar.set(Calendar.DAY_OF_MONTH, 1);
chosen_date= calendar.getTime();
//good luck
First of all better use a PreparedStatement. Then simply compare the dates of the with the first day of the month and the first day of the next month (assuming the type of the month_arv column is DATE):
LocalDate date = ...
LocalDate startOfMonth = date.withDayOfMonth(1);
LocalDate startOfNextMonth = startOfMonth.plusMonths(1);
// save for later use (insertion)
Date sqlStartOfMonth = Date.valueOf(startOfMonth);
PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM doc_arriv WHERE month_arv >= ? AND month_arv < ?");
statement.setDate(1, sqlStartOfMonth);
statement.setDate(2, Date.valueOf(startOfNextMonth));
ResultSet res = startment.executeQuery();

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

How to find last / 7 /30 days records of sqlite db when datetime is stored as text?

I have an activity where i save some info to my database.
I have two textviews one for date (yyyy-MM-dd) and one for time (HH:mm).
if i save datetime as a TEXT, i can sort then desc properly,but CAN i find with sqlite query last/7/30 days records?An example of this query when are the datetime TEXT?
First you should calculate the date range you want to analize, then convert its boundaries into the text format (you can use some date formatting ustilities). Then you should query the Db with converted dates as parameters.
Suppose you want last 30 days list:
Calendar theEnd = Calendar.getInstance();
Calendar theStart = (Calendar) theEnd.clone();
theStart.add(Calendar.DAY_OF_MONTH, -30);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String start = dateFormat.format(theStart.getTime());
String end = dateFormat.format(theEnd.getTime());
// Now you have date boundaries in TEXT format
Cursor cursor = db.rawQuery("SELECT * FROM table WHERE timestamp BETWEEN "+start+" AND "+end);

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