how to compare joda Datetime in hql - java

consider this hibernate field:
#Column(name="datecreated", nullable = false)
#org.hibernate.annotations.Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime dateCreated;
i want to run an hql query like this:
String query = "select ticketEvent " +
"from TicketEvent ticketEvent " +
"where ticketEvent.status = :status " +
"and ticketEvent.dateCreated > :highestTicketCommentDate " +
"and ticketEvent.ticket.id = :ticketId " +
"order by ticketEvent.id DESC";
ticketEvents = (List<TicketEvent>) entityManager.createQuery(query)
.setParameter("ticketId", ticket.getId())
.setParameter("status", TicketEvent.Status.SAVED)
.setParameter("highestTicketCommentDate", highestTicketCommentDate)
.getResultList();
here highestTicketCommentDate is also a joda DateTime. but I am getting wrong results. what is the correct way to compare hql joda datetime? any help would be appreciated.
thanks in advance

Related

MySQL SELECT WHERE... AND (based on parameter value)

#Query(value =
"SELECT * " +
"WHERE (type REGEXP ?1) " +
"AND status= ?2 " +
"AND date(createdAt)..." +
"ORDER BY id DESC " +
"LIMIT ?4",
nativeQuery = true)
Optional<List<Item>> findLatest(String type, String status, String date, int limit);
I have this query where I'd like to filter by createdAt, only if the date value from the parameter is not null.
If String date = null, the query should not consider the AND date(createdAt)...
However if String date = "today" the query should include something like AND date(createdAt) = CURRENT_DATE
How can I achieve this?
Simplified you can make
If you have more choice you need case when
The idea is when the condition is not met, we let the and part always be true
so that the where calsue is true if all the other conditions are met
SELECT * FROM
A
WHERE
status= 72
AND IF( date = "today" , date(createdAt), current_date) = current_date
The way we usually handle this is by adding a logical check to the WHERE clause which allows a null date.
#Query(value = "SELECT * " +
// ...
"WHERE (type REGEXP ?1) AND " +
" status = ?2 AND " +
" (DATE(createdAt) = ?3 OR ?3 IS NULL) " +
"ORDER BY id DESC " +
nativeQuery = true)
Optional<List<Item>> findLatest(String type, String status, String date);
Note that it is not possible to bind parameters to the LIMIT clause, therefore I have removed it. Instead, you should use Spring's pagination API.

Bind #param in a Jpa repository native query inside single quotations

I am looking for a way to bind a given param in a native query where the value has to be inside single quotations, like so:
#Transactional(readOnly = true)
#Query(value = " SELECT c.ID " +
" FROM table1 clh " +
" LEFT JOIN table2 nks " +
" on clh.SERIAL = nks.SERIAL_REF " +
" WHERE clh.CREATED_DATE >= :now - interval ':timeThreshold' HOUR " +
" AND nks.SERIAL_REF IS NULL" , nativeQuery = true)
List<Long> getIdsWithoutAnswer (#Param("timeThreshold") Integer timeThreshold, #Param("now") LocalDateTime now);
However, when I try to run this, it results in hibernate not being able to bind the timeThreshold value as it is provided inside the single quotations ''.
Does anyone know how this can be resolved?
The problem you are having with your native Oracle query has to do with trying to bind a value to an interval literal. You can't do that. Instead, use the NUMTODSINTERVAL() function:
#Transactional(readOnly = true)
#Query(value = " SELECT c.ID " +
" FROM table1 clh " +
" LEFT JOIN table2 nks " +
" on clh.SERIAL = nks.SERIAL_REF " +
" WHERE clh.CREATED_DATE >= :now - numtodsinterval(:timeThreshold, 'hour') " +
" AND nks.SERIAL_REF IS NULL" , nativeQuery = true)
List<Long> getIdsWithoutAnswer (#Param("timeThreshold") Integer timeThreshold, #Param("now") LocalDateTime now);

query date by month and year with hibernate from database

i have a named query where I want to fetch all records where year and month of a parameter match the database entry:
#NamedQuery(
name = entries.queryX,
query = "SELECT DISTINCT t from entries t " +
"where MONTH(t.myMonth) = :month " +
"and YEAR(t.myMonth) = :year "
)
The value "myMonth" in table entries is a YearMonth:
#Column(name = "MY_MONTH", precision = 7)
private YearMonth myMonth;
I set the query parameters as follows:
query.setParameter("month", date.get(Calendar.MONTH) + 1);
query.setParameter("year", date.get(Calendar.YEAR));
However, this approach does not work... Is there any other way to implement what I want to search for?

Spring data jpa, Native Query, returned wrong field types

I have following native query method in my repository:
#Query(value="SELECT appSub.ApplicationFormId as appFormId, appSub.profileId as profileId, "
+ "p.CASId as profileCASId, ps.programId as programId FROM [unicas_config].[dbo].ApplicationFormEarlyDecisionConfig appFormED "
+ "INNER JOIN [unicas_ux].[dbo].ApplicationSubmission appSub ON appFormED.ApplicationFormId = appSub.applicationFormId "
+ "INNER JOIN [unicas_ux].[dbo].Profile p ON appSub.profileId = p.id "
+ "INNER JOIN [unicas_ux].[dbo].ProgramSelected ps ON p.id=ps.ProfileId AND appSub.applicationFormId = ps.instanceId "
+ "WHERE appFormED.EarlyDecisionVerdictDate >=:fromDate AND appFormED.EarlyDecisionVerdictDate <:toDate "
+ "AND appSub.EarlyDecisionStatus='Applied Early Decision' "
+ "AND appSub.ApplicationStatus='Received' "
+ "AND ps.IsPaid =1 "
+ "ORDER BY appSub.ApplicationFormId",nativeQuery = true)
List<Object[]> getAllEarlyDecisionApplicantsWithPaidProgramsOnVerdictDate(#Param("fromDate") Date fromDate, #Param("toDate") Date toDate);
Now, I want to map the returned result:
long appFormId = (Long)obj[0]
long profileId = (Long)obj[1]
long programId = (Long)obj[3]
When I am doing that, I am getting java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long as Hibernate consider these ids of Integer type instead of Long.
Please, tell me how could I programatically tell Hibernate to return proper type.
To be on the safe side, I always cast numeric types to Number and then get the value of desired type from it, as JDBC driver can return Integer, Long, BigDecimal, etc. depending on the type of the database column:
((Number) obj[0]).longValue()
Of course, don't forget to check for null if column is nullable.

Hibernate Group By Query

Please help me understand whats wrong with this query.
String sql = "select d.arc_alrt_cde, d.alrt_desc, count(d.arc_alrt_cde) " +
"from arc_alrt a, arc_alrt_def d " +
"where d.arc_alrt_cde = a.alrt_cde " +
"and (a.stat_cde = 'OPEN' or a.stat_cde = 'RE-OPENED') " +
"group by d.arc_alrt_cde, d.alrt_desc "+
"order by count(d.arc_alrt_cde) desc"
println sql
Query query = session.createQuery(sql);
Printing SQL
sql = select d.arc_alrt_cde, d.alrt_desc, count(d.arc_alrt_cde) from arc_alrt a, arc_alrt_def d where d.arc_alrt_cde = a.alrt_cde and (a.stat_cde = 'OPEN' or a.stat_cde = 'RE-OPENED') group by d.arc_alrt_cde, d.alrt_desc order by count(d.arc_alrt_cde) desc
Getting the following error. Tried IN clause also.. Not working..
Error:
java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:64)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:300)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
That's an SQL query not a HQL one, so you should use:
SQLQuery query = session.createSQLQuery(sql);
That exception you got is thrown because Hibernate expects an HQL query but receives an SQL query instead.
You are to name the count field such as count(d.arc_alrt_cde) as countOfXXX
and also your entity should be aligned with that query or you should remove that count field at all.
Changed it to use object properties and it worked. Thanks for your inputs.
String sql = "select alert.alertCode, def.alertDesc, count(alert.alertCode) " +
"from ArcAlert as alert, ArcAlertDef as def " +
"where alert.alertCode = def.alertCode " +
"and alert.status in ('OPEN', 'RE-OPENED') " +
"and alert.assignedTo = '"+assignedTo+"' " +
"group by alert.alertCode, def.alertDesc " +
"order by count(alert.alertCode) desc"
Query query = session.createQuery(sql);
lst = query.list()

Categories

Resources