how to use date() in hibernate criteria - java

I would like to use Date() function in hibernate criteria, since one field is timestamp.
My sql would be:
"select * from feed where DATE(date) = DATE(NOW()) + INTERVAL 5 DAY"
When I try in criteria:
critera.add(Restrictions.eq("DATE(date)", "DATE(NOW()) + INTERVAL 5 DAY"));
I get:
could not resolve property: DATE(date) of: com.mycomapany.model.Feed
I have there in feed a field by the name date.
What is the problem? I am using MySQL

The best solution is to use the criteria api which you started to use.
Calendar c = Calendar.getInstance(LOCALIZATION);
//Add 5 Days
c.add(Calendar.DATE, 5);
criteria.add(Expression.ge("dateColumn",c.getTime());

You could probably find a way to make this work, but in my opinion, this is the wrong way to approach it.
One of the major features of Hibernate is the abstraction of the database-vendor-specific features, via the Hibernate Dialect.
You are attempting to access MySQL features directly, but through the vendor-neutral interface, thus your difficulty. Hibernate could have support for date intervals , but does not - see https://hibernate.onjira.com/browse/HHH-2434
So, the options seem to be:
Calculate the date ranges in your code, rather than in the HQL
Do what you need to do in SQL rather than HQL
Create a custom Hibernate Dialect, as in Performing Date/Time Math In HQL?

Using Joda Time:
public List<Feed> findByDaysFromToday(int daysFromToday) {
return em.createQuery(
"SELECT f FROM Feed f WHERE f.date BETWEEN :start AND :end")
.setParameter("start",
new LocalDate()
.toDateMidnight()
.toDate(),
TemporalType.DATE)
.setParameter("end",
new LocalDate().plusDays(daysFromToday)
.toDateMidnight()
.toDateTime()
.minusMillis(1)
.toDateTime()
.toDate(),
TemporalType.DATE)
.getResultList();
}

Related

Hibernate Criteria - How to apply functions to ORDER BY?

It sounded like a simple problem, but I found no easy solution online.
I am trying to replicate the current ORDER BY in Hibernate, without succes:
SELECT * FROM IPEM.DEMANDE
WHERE INIT_DATE >= TO_TIMESTAMP('23/04/2021', 'dd/MM/yyyy') AND INIT_DATE <=
TO_TIMESTAMP('29/04/2021', 'dd/MM/yyyy')
ORDER BY TO_TIMESTAMP(LIMIT_DATE, 'dd/MM/yyyy'), TO_TIMESTAMP(INIT_DATE , 'dd/MM/yyyy') ASC <<< this line
Why ? Because I have this kind of data in my database:
05/05/2021 00:00:00 - 23/04/2021 00:00:00
05/05/2021 00:00:00 - 28/04/2021 00:00:00 << this should be 3rd
05/05/2021 02:00:00 - 24/04/2021 00:00:00 << this should be 2nd
The hours mess up the sorting. I'm trying to ignore them/format the date before loading my entries. A way I found to do so is applying TO_TIMESTAMP to ORDER_BY. It works well in SQL, but when going to Hibernate, it is not that simple.
Actually, my code looks like this:
criteria.addOrder(Order.asc(fieldName));
I tried some trivial solution, which obviously did not work:
criteria.addOrder(Order.asc("TO_TIMESTAMP(" + fieldName + ", 'dd/MM/yyyy')");
For which I had the following error (limitDate is the Java name, LIMIT_DATE the corresponding column):
org.hibernate.QueryException: could not resolve property: TO_TIMESTAMP(limitDate, 'dd/MM/yyyy')
How can I apply TO_TIMESTAMP to the members of my ORDER BY ? (No worries, we assume here all the members are dates, both in Java and in the SQL Table).
That's not possible, but you can subclass Order and override the org.hibernate.criterion.Order#toSqlString method to implement whatever logic you need. Anyway, you should move away from the legacy Criteria API to the JPA Criteria API. There you could use criteriaQuery.orderBy(criteriaBuilder.function("TO_TIMESTAMP", root.get(fieldName), criteriaBuilder.literal("dd/MM/yyyy")))

EclipseLink - Add Days in Date Using CriteriaBuilder

I'm using eclipselink 2.1 and I would like to get a little help in CriteriaBuilder,
How can I do this SQL ruler in Criteria API ?
AND TRUNC ( e008.atdt_008dtinclusao + e008.atni_008nro_dias_visual ) >= TRUNC (SYSDATE)
The first field is a Date, in my entity is a Joda DateTime
The Second field is a Integer is a number of date to view.
I can not sum and truncate this part with the Criteria.
Thank you for the attention and help.
Using org.eclipse.persistence.expressions.ExpressionBuilder I could do:
ExpressionBuilder officeExpression = new ExpressionBuilder(OfficeEntity.class);
officeExpression.anyOf(OfficeFields.judicialNotifications);
officeExpression.anyOf(OfficeFields.eventsHistoric);
officeExpression.anyOf(OfficeFields.contracts);
.and(ExpressionMath.add(officeExpression.get(OfficeFields.judicialNotifications).get(JudicialNotificationFields.dateInsert).toDate()
, officeExpression.get(OfficeFields.judicialNotifications).get(JudicialNotificationFields.daysViewer)).equal(JodaTimeHelper.now().toDate()))

Mysql alike date functions in Morphia

I am in progress of migration a JPA/MySQL application to mongodb using morphia. I have some queries like
AND DATE(NOW()) > (DATE(created) + 2)
or
AND ( TIMESTAMPDIFF(MINUTE,kickoff,now()) > 1 )
or
AND DATE(ending) = DATE(NOW())
Is there anything similar in morphia or mongodb?
From your question I understand that you ask for a way to create date queries in MongoDB and how would your write that query in Morphia
The Cookbook for date queries can be found here.
As pointed in the above post, you should use a range query for this.
In MongoDB's shell, for your first query, you would write it like this:
// hope I got the date part right XD
db.posts.find({created: {$lt: new Date().getDate() - 2}});
For range queries morphia has 2 ways:
using the filter method
using directly the comparator methods.
So the first query would become something like this:
myObjDao.createQuery().field("created").lessThan(new Date(System.currentTimeMillis() - 2 * 24 * 3600 * 1000 )).fetch();

db4o query optimisation for a scheduling application

I'm just getting started with db4o in a scheduling application and I'm looking for an efficient way to retrieve rooms which are not booked between certain dates.
So, I have a collection of Room objects each of which has a collection of Booking objects (which can be empty). A Booking has a start date and and end date. I want to say 'get all the rooms that have no Bookings between DateA and DateB'.
I'm sure I could do this using a Native Query but since there's a date range involved (my understanding is date ranges aren't optimzed for NQ) and I need to do this query very frequently (many times per second for potentially more 10,000 rooms - the majority of which have no Bookings) I'm looking for more efficient alternatives.
Is there a way to phrase this using SODA?
Or a better way to arrange my data model to get round this issue?
Yes you can do this by using SODA Query
Date fromDate = null ; // assign reservation start dat
Date toDate = null ; // assign reservation upto
Query query = db.query();
query.constrain(Booking.class);
query.descend ("fromDate").constrain ( fromDate ).greater().equal ().
and (query.descend ("toDate").constrain (toDate).smaller().equal());
ObjectSet<Booking> objectSet = query.execute();
Query for all of the rooms which do not have a booking between fromDate and toDate
Query query = db.query();
query.constrain(Room.class);
query.descend ("bookingStartDate").constrain ( fromDate ).greater().equal ().and
(query.descend ("bookingEndDate").constrain (toDate).smaller().equal()).not();
ObjectSet<Room> objectSet = query.execute();
See Also : Building SODA Queries

Google app engine java filtering date query with day

I am looking for some thing like this.
public class User
{
private Date createdOn;
}
Now i need a query to fetch users created on day 10th of any month or year.
Like i need users created on 10th Jan 2012, 10th Feb 2012, 10th June 2010.....
How can i get part of a date in gae query?
Thanks,
Ramesh.V
Just create a date object for whatever date you're looking for and use it as part of the query. There's nothing special about Dates in queries.
Not sure if you're using JDO, JPA or the datastore directly, but either way
See the GQL reference (not really python specific): http://code.google.com/appengine/docs/python/datastore/gqlreference.html
SELECT * FROM User WHERE createdOn == :date
In JDO it would look something like:
Query query = pm.newQuery(User.class);
query.setFilter("createdOn == dateParam");
List<User> results = (List<User>) query.execute(date);
For your filter, you could use:
"(createdOn >= p1) && (createdOn <= p2)"
where you have set the parameters p1 and p2 to be the start and finish Dates of the day in question.

Categories

Resources