Group by date - jpa2 - postgres - java

I'm struggling to find a proper example to group by date instead of date time in a jpql. Note that I am connecting to a postgres db.
Query looks as follows:
#Query("select new example.model.ExampleModel(te.dateCreated, te.transactionStatus, sum(te.amount), count(te)) from ExampleEntity te group by te.dateCreated, te.transactionStatus")
fun findAggregatedExamples(): List<ExampleModel>
I need to convert the contructor arg to date and the group by to date.

Managed to find something useful in here
Working Code:
#Query("select new example.model.ExampleModel(cast(te.dateCreated as date), te.transactionStatus, sum(te.amount), count(te)) from ExampleEntity te group by cast(te.dateCreated as date), te.transactionStatus")
fun findAggregatedExamples(): List<ExampleModel>
Constructor arg0 had to be changed from LocalDateTime to java.util.Date.

Related

Spring Querying DateTime by Date

I am fairly new to spring so maybe I am missing the wrong terminology and that is the reason why my searches brought nothing up.
The Query I am looking for should Take a parent object and remove all Child objects where a timestamp is not of a specific date.
Parent Id field1 field2
Child: Id parentId field 1 timestamp (datetime)
I tried several different approaches but nothing seems to work.
Alternatively I could try something like:
FindAllChildsByIdAndTimestamp(int id, Date date)
And fill a empty Parent with the data. But event hat does not work.
Any Idea what i am doing wrong?
Best and Thank you
You don't even need to bring a parent into this. All you need to do is to create a query on a child table and generate a query on that table with where clause would be parentId is and timestamp is . You mentioned that you are using Spring (which version BTW?) but didn't say what do you use to access your DB (Spring Data, Hibernate, JPA, JBC?) Also which DB and which version? I will give you example in Hibernate:
sessionFactory.getCurrentSession().createCriteria(Child.class)
.add(Restrictions.eq("parentId", yourParentId))
.add(Restrictions.gt("timestamp", date1))
.add(Restrictions.le("timestamp", date2))
.list();
date1 is midnight of your day and date2 is midnight of the following day. This should give you the list of your children
I solved the problem by seperating the two requests.
public interface ChildRepository extends CrudRepository<Child, Serializable> {
List<child> findAllBytimeStampBetweenAndParent(Date dayBegin, Date dayEnd, Parent parent);
And then attributed it to the parent
Parent parent = this.getById(id);
// Convert Date Type
DateTime dayTimeEnd = new DateTime(date);
dayTimeEnd = dayTimeEnd.plusHours(23);
dayTimeEnd = dayTimeEnd.plusMinutes(55);
Date dayEnd = dayTimeEnd.toDate();
// Get all Tracking Data of this Date
List<Child> ChildList = this.childRepository.findAllBytimeStampBetweenAndParent(date, dayEnd, parent);
as an alternative i could have used direct queries.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Spring Boot MongoRepository query via Date with Criteria lt & gte gives wrong result

When I query MongoRepository via Date field with Criteria in a Spring Boot application, the result is wrong. Here is my method:
Query query = new Query(new Criteria().andOperator(
Criteria.where("id").is(filter.getId()),
Criteria.where("datas.ts").lt(filter.getEndTime()).gte(filter.getStartTime())
));
List<PhaseData> phaseDatas = mongoOperations.find(query, PhaseData.class);
List<Data> result = new ArrayList<Data>();
for(Data pData : phaseDatas) {
result.addAll(pData.getDatas());
}
return result;
When I query with
{
"id" : "1234",
"startTime" : "2016-08-04 12:00",
"endTime" : "2016-08-04 15:00"
}
it gives me records with hour 16:54 & 21:12 too. How can I solve this issue?
Not sure if this addresses your question directly.
The DB won't return wrong result to the query. So I think it could be one of the following things:
It could be that the when you view the documents in mongodb, it displays date in iso format. So view the documents in the same format as you are creating dates for your query.
It could be timezone issue.
Mongodb dates can be considered as ISODate (MongoDB Date)
When you query, you create date objects in your timezone. So as a first debugging measure, I would see if both my DB and query timezones are the same.
Also, probably it would help if you query by creating date objects in ISODate by using SimpleDateFormat(SDF is not thread safe).
I have found that it could be confusing because the dates that you send are in a different format and the documents that you visually see in mongodb tool are displaying dates in iso format. I think that it could be the issue. The results are good, but probably you are viewing the two things differently and it causes the confusion.

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

Empty result set from a Compass Lucene query with Dates

I am using Compass to make queries on data inside in memory data structure. It works fine for searching String and enum values, now I want to search dates.
Search criteria are annotated by #SearchRestriction annotation. Example about someDate:
#SearchRestriction(path="fooBar.someDate" type = SearchRestrictionType.EQUAL)
String someDate;
At searchable data SomeDate is annotated like the following:
#SearchableProperty
Date someDate;
SomeDate inside the searchable data is generated with new Date();) and query String is given as 20120802.
Situation on debugger:
This code generates queries like this:
someDate:20120802
Here someDate is the name of the field I am looking for and 20120802 is a date in order yyyyMMdd.
Problem:
No results is returned, when this query is run. I get an empty list. The Date in query is the same as in the Date object.
What is wrong??
Is this wrong way to search Dates with Compass? I can find only range queries about Date, but a search with exact Date or part of exact Date I cannot find.
You need to specify the format for Searchable property [Date]
#SearchableProperty(format = "yyyyMMdd")
To some extent, it relates to Grails: Lucene, Compass Query Builder and date ranges

how to use date() in hibernate criteria

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

Categories

Resources