How to use cast in HQL OR JPQL? - java

Hi,my HQL query is like this.
#Query("select A.TheaterName as theater,A.MovieName as movie,CAST(A.ShowDateTime as showDate)" +
"(select sum(TicketPrice) from ccmsfdb2.HallApi.TicketTransaction where \n" +
"CAST(ShowDateTime as date)=CAST(A.ShowDateTime as Date) AND\n" +
" MovieName=A.MovieName and TheaterName=A.TheaterName and TicketStatusValue=1) as collection\n" +
"from CCMSFDB2.HallApi.TicketTransaction A where A.MovieName='Sanju' \n" +
"and A.TheaterName='QFX Jai Nepal' \n" +
"group by CAST(A.ShowDateTime as date),A.TheaterName,A.MovieName,CAST(A.ShowDateTime as Date) order by showDate DESC")
List<MovieCollectionAccordingToTheaaterDto> getMovieCollectionAccordingToTheater();\
In the above query ,I have tried to cast showdatetime as date and sum the gross collection according to date but cast is not supported in hql and i don't want to use native query.

CAST is supported in HQL, given that the underlying DB supports it.
Try full-qualified class name for Date(java.util.Date) inside the #Query expression.
See :
1. HQL Expressions

Related

How can I set a date variable with normal string variables in my jpql code?

I have a query that has to be executed in my application. On the front end side, a user should be able to make a search in the search bar. Every time he will write in the search box, we will automatically take this input and send a request to retrieve the corresponding data. The problem here is the date, the user should be able to select the data returned according to the specific categories. When he select a date, all the products with this corresponding date have to be returned.
This is the code below:
String sql = "SELECT t FROM tables t WHERE (t.a LIKE ?1 OR "
+ " t.b LIKE ?1 "
+ "OR t.c LIKE ?1 "
+ "OR t.d LIKE ?1 OR t.e LIKE ?1 "
+ "OR t.f LIKE ?1 "
+ "OR t.g LIKE ?1 "
+ "OR t.u_date LIKE TO_DATE(?1,'dd/MM/yyyy') "
+ "OR t.y_date LIKE TO_DATE(?1,'dd/MM/yyyy') ) "
+ "OR t.num LIKE ?2)";
lstMvt = em.createQuery(sql)
.setParameter(1,isDate == true ?search_value:search_value+"%")
.setParameter(2, num+"%")
.setFirstResult(start)
.setMaxResults(limit)
.getResultList();
In my code, I have written a helper function to check whether the search value entered is a date or a normal string. So when injecting the parameters, isDate variable tells me that if the search is true(a date) then inject it directly but if it is a normal string inject it with % as it is a LIKE clause.
The problem is being caused by the dates variable in the query. When I search with a date value in the search box the data return correctly, but when I try to search with a non-date value, an exception is thrown. I know the problem is from the dates variables because I had commented them to test and it was working properly.

Java convert Postgres query into JPA Criteria builder

I have this sql query which I am using native sql to process currently and I need to transform it to use the JPA criteria builder so I can dynamically build up the where conditions. I am currently semi building the conditions dynamically in a janky way in sql (AND (case when 0 in :#{#filter.modelIds} then true else model_id in :#{#filter.modelIds} end)
Also, Im not sure what the best practices are and if I should just leave the code I currently have or move it over to Criteria builder. A lot of articles I read have said not to use criteria builder for advance quires. For me everything works but some people expressed concerns over the maintainability of the code. To me I like looking at sql versus the criteria builder just confuses me :)
Another blocker for me is I'm using the Postgres function generate_series to create all the dates in a date range so that way I can have empty values for dates with no data. I was not sure how to translate this over to the criteria builder I figured out how to use the date trunc function Expression<Date> view_date = builder.function("date_trunc", Date.class, builder.literal("day"), root.get("acquisitionDate")); The only other thought I had was to just execute the sub query and the use java to build up the date array and map my results to it
SQL:
select date, COALESCE(views, 0) as count, model_id
from generate_series(date '2020-05-9',date '2020-05-18',interval '1 day')as t(date)
left join (
select date_trunc('day',acquisition_date) as view_date, count(acquisition_date) as views, model_id
from view
where acquisition_date between '2020-05-9' and '2020-06-19'
group by model_id, view_date
order by view_date asc
) as v on v.view_date = date
order by date asc;
Repository:
#Query(
value = "select date, COALESCE(views, 0) as count, d.model_id as itemId " +
"from generate_series(date (:#{#filter.startDate}),date (:#{#filter.endDate}), CAST('1'||' '||:#{#filter.getInterval()} AS Interval))as t(date)" +
"left join (" +
"select date_trunc((:#{#filter.getInterval()}),acquisition_date) as view_date, count(acquisition_date) as views, model_id " +
"from view " +
"WHERE acquisition_date between (:#{#filter.startDate}) and (:#{#filter.endDate})" +
"AND (case when 0 in :#{#filter.modelIds} then true else model_id in :#{#filter.modelIds} end)" +
"AND (case when '0' in :#{#filter.imageIds} then true else image_id in :#{#filter.imageIds} end) " +
"AND (case when 0 in :#{#filter.objectIds} then true else object_type_id && array[(:#{#filter.getObjectArray()})] end)" +
"group by model_id, view_date " +
"order by view_date asc" +
") as v on v.view_date = date_trunc((:#{#filter.getInterval()}), date) " +
"order by date asc",
nativeQuery = true
)
List<ItemDateCountProjection> getModelViewsByDate(#Param("filter") ViewFilter filter);
Projection
public interface ItemDateCountProjection {
String getItemId();
Integer getCount();
Date getDate();
}

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.

Number of characters in sql query result

I am using Spring 3.1.1 with Hibernate 4 and a MSSQL database. Finally, I have been able to query my database with joins in my table that returns the correct answers. Although, it seems that it does not return the entire strings of my messages, but cuts at 29/30 digits. Here is my query:
SQLQuery sql = this.getCurrentSession().createSQLQuery(
"SELECT event.id as eventid, CAST(event_type.type_name AS varchar) as eventtype, event.check_date, event.event_date, event.status, CAST(event_message.message AS varchar) as eventmessage " +
"FROM event_log event " +
"LEFT JOIN event_type " +
"ON (event.event_type_id = event_type.id) " +
"LEFT JOIN event_message " +
"ON (event.event_message_id = event_message.id) " +
"WHERE event.event_type_id = " + jobId +
"ORDER BY eventid");
The result can be:
4506 Database 2014-01-15 14:14:15.02 2014-01-15 14:14:15.02 false Database-connection cannot be
Where the columns are id, task_name, check_date, event_date, status and the message-string at the end. .
The result goes to a ArrayList<Object[]> where I read row[0] etc. to get the entities in the row. The string message gets cut after 29 digits, which is disturbing. Why does it cut the string and how can I fix this? In my database the string exists in it's full and is entitled 400 characters max.
I know this is probably not the best way to query my database, but it will do for my application since it works.
You are using varchar without a length. Never do this!
Replace:
CAST(event_type.type_name AS varchar)
With something like:
CAST(event_type.type_name AS varchar(255))
In some contexts, the default length is 32. In some it is 1. In general, though, always specify the length.
EDIT:
Actually, you probably don't even need the cast. Why not just have event_type.type_name in the select list?

Using a java.sql.Timestamp object in an sql query

I am trying to run a query in java that uses a java.sql.Timestamp object as the date to compare with in the where clause.
Here is how the query string that is built in Java
String getTransactionsSQL = "Select transaction_seq " +
"From transactions ct " +
"Where id = 'ABCD'" +
"And ct.out_msg_timestamp" +
"<= to_date('" + parseDate.getTimeStamp() +"','YYYY-MM-DD HH:MI:SS..')" +
"order by transaction_seq";
The statement parseDate.getTimeStamp() returns a java.sql.TimeStamp object that contains a date. Here is an example output of System.out.println(parseDate.getTimeStamp());
2011-03-07 05:47:57.0
When i run the above query i get this error
java.sql.SQLException: ORA-01843: not a valid month
Any clues?
Use PreparedStatement: http://download.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
Never use string concatenation to pass arguements to SQL commands (security risk: SQL injection)!

Categories

Resources