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();
Related
I am trying to get all objects by specific month and year.
I have done this with Native Query
#Query(value = "select * from transaction_log as t where year(t.insurance_period)=(:year) AND user_id =(:userId) AND t.employer_id is null", nativeQuery = true)
And I want to be done with another way so I can use entity graphs etc.
I have try
#Query("select t from Transaction t where year(t.insuranceDate) = ?1 and month(t.insuranceDate) = ?2")
And I get error on method Year () for unexcepted '('
and the following with the same error at EXTRACT method.
#Query("SELECT t FROM Transaction t WHERE EXTRACT (YEAR FROM t.insuranceDate) = :year AND EXTRACT (month FROMt.insuranceDate) = :month")
You could use BETWEEN first day of month and last day of month. According to jpql doc BETWEEN is inclusive.
The downside is doing some date calculations, but they are trivial with java.time classes. Let's say you want dates from February 2020. You could get first and last day like this:
int year = 2020;
int month = 2;
LocalDate firstDay = LocalDate.of(year, month, 1);
LocalDate lastDay = firstDay.withDayOfMonth(firstDay.lengthOfMonth());
Then the query will look like this:
#Query("SELECT t FROM Transaction t WHERE t.insuranceDate BETWEEN :firstDay AND :lastDay")
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);
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();
i want to write a query to compare a given date with today date with timestamp.
given date can be the today date, if the date is same it will compare the time.
select * from abcTable where submitDate <= now();
here its comparing only the date not the time.
submitDate is anydate which is in the db table.
Firstly, you have specified that column submitDate is of datatype Date while, as per your question its datatype should be Timestamp.When the datatype of submitDate column is Date, there is no reason to even compare the time.
However if you need to still want to compare the submitDate with current timestamp, you can do it this way:
select * from submitDate where date_format(submitDate,'%d/%m/%y %T') <= now();
Edit: The above query is for Mysql
I think you should try:
GETDATE() --2017-01-17 08:19:28.403
you can get day, month and year separately by doing:
select DAY(getdate()) --17
select month(getdate()) --1
select year(getdate()) --2017
if you are on sql server 2008, there is the DATE date time which has only the date part, not the time:
select cast (GETDATE() as DATE) --2017-01-17
OR you you can try:
select * from abcTable where submitDate <= CAST(CURRENT_TIMESTAMP AS DATE);
OR
select * from abcTable where submitDate <= cast((now()) as date);
Am trying to get datetime difference with joda time (ie startdate -2014-02-26 and enddate-2014-02-26) for a day but i keep on getting a blank table.When i change to startdate -2014-02-26 and enddate-2014-02-27 data gets displayed. below is sample code
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date todaydate = new Date();
DateTime jodaToday = new DateTime(todaydate);
String datefrom = sdf.format(jodaToday.toDate());
String dateto = sdf.format(jodaToday.plusDays(1).toDate());
and my query looks like below.
ProductTable.setContainerDataSource(storeData(
"SELECT * FROM sales where sale_time BETWEEN '"
+ datefrom + "' AND '" + dateto + " ' ORDER BY sale_time DESC"
));
What could i be missing ?
NOTE: When i do a test with the below query i get data
SELECT * FROM sales WHERE sale_time BETWEEN
'2014-02-26 00:00:00' AND '2014-02-26 23:59:59' ORDER BY sale_time DESC;
Thanks
Your problem is more about understanding the BETWEEN SQL statement. In simple words, BETWEEN can be explained as:
FOO BETWEEN A AND B
Which is equivalent to
FOO >= A AND FOO <= B
With this in mind, if you have sale_time >= '2014-02-26' AND sale_time <= '2014-02-26', it will be understood by your database engine as sale_time >= '2014-02-26 00:00:00' AND sale_time <= '2014-02-26 00:00:00'. So, the database engine won't be able to find a row which sale_time value is '2014-02-26 05:32:16' or similar.
After understanding this, then you're able to understand why setting the second parameter of your between works when you add one day to today. The SQL statement would be:
sale_time BETWEEN '2014-02-26' AND '2014-02-27'
Which can be understood as:
sale_time >= '2014-02-26 00:00:00' AND sale_time <= '2014-02-27 00:00:00'
I don't know vaadin but you should use a method where you will send these Strings as parameters rather than concatenating them to generate the query to execute. Note that if you do this more and more your application is prone to SQL Injection.
Data from midnight to midnight:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateTime from = new DateTime(2014, 2, 26, 0, 0).withTimeAtStartOfDay();
DateTime to = from.plusDays(1).withTimeAtStartOfDay().minusSeconds(1);
String datefrom = sdf.format(from.toDate());
String dateto = sdf.format(to.toDate());
EDIT
Maybe the extra space is the problem:
...dateto + " ' ORDER BY...
^
Little bit difficult to give an answer without the Table and data,
Set break point to the "datefrom" and check whether correctly set "datefrom" and "dateto".
Check the Table column DATE or TIMESTAMP.
Check data is available in table match your criteria.
Get this query and set hard-coded "datefrom" and "dateto" and execute as a SQL query in your DBMS.
The below is the solution that worked. Note added timestamp(23:59:59) in bold.
" AND sale_time >= '"+sdf.format(fromdate.getValue())+"' AND sale_time <= '"+sdf.format(Todate.getValue())**+" 23:59:59'"**;