Converting query result to Entity - Spring Boot/JPA [duplicate] - java

I'm trying to get some values from a H2 db table.
The query which does what I need is this:
SELECT cast(creationDate as date) as DATE, SUM(paymentValue) as TOTAL,fxRate
FROM payment
group by DATE
where "creationDate", "paymentValue", "fxRate" are columns of the table "payment".
CreationDate is a timestamp so I have to get only the date from it.
When I try to write it in Java
#Query("SELECT cast(creationDate as date) as daydate , SUM(paymentValue) as value1, fxRate as value2 FROM payment " +
"group by cast(creationDate as date)")
List<Payment> findPaymentValuePerDay ();
I get the error [Ljava.lang.Object; cannot be cast to ...entity.Payment.
I also tried to use a different object called GraphDto which has as attributes daydate, value1 and value2
#Query("SELECT cast(creationDate as date) as daydate , SUM(paymentValue) as value1, fxRate as value2 FROM payment " +
"group by cast(creationDate as date)")
List<GraphDto> findPaymentValuePerDay ();
but I get the same error.
[Ljava.lang.Object; cannot be cast to ...entity.GraphDto.
so, how can I work with alias in JPQL?? I just need a function that returns 3 different columns' name with values took from an existing entity using the right H2 query.
Thank you all

Your query return an array of Object[] and not GraphDto Object, you have multiple ways to solve this problems :
Solution 1
Create a constructor which hold daydate, value1, value2
#Entity
public class GraphDto{
private Date daydate;
private Long value1;
private Long value2;
public GraphDto(Date daydate, Long value1, Long value2){
//...
}
//..getters and setters
}
then your query should look like this :
SELECT NEW com.packagename.GraphDto(cast(creationDate AS date), SUM(paymentValue), fxRate)
FROM payment
GROUP BY cast(creationDate AS date)
Solution 2
change the return type to :
List<Object[]> findPaymentValuePerDay ();
Then in your service loop over this object and extract the values :
List<Object[]> listObject = rep.findPaymentValuePerDay();
for(Object[] obj : listObject){
Date date = (Date) obj[0];
Long value1 = (Long) obj[1];
Long value2 = (Long) obj[2];
}

Related

JPA Query for fomat Date

In Data base , createdDt is storing formated like:
15-01-20 10:43:20.394000000 AM
I am passing "created" as dd-mm-yyyy
I want to take the matching date from the table(without comparing time)
#Query("SELECT p FROM ABC p WHERE ( COALESCE(:created) is null or p.createdDt = :created) order by p.createdDt desc")
List<ABC> filterABC(#Param("created") Date created);
How to parse the date within query ?
You could try to use native query using specific DBMS stuff to extract date part.
#Query(value = "SELECT * from ABC where DATE_FORMAT(createdDt, '%d-%m-%Y') = ?1", nativeQuery = true)
List<ABC> filterABC(Date created);
DATE_FORMAT is MySQL specific function. Use the appropriate date function in accordance with your DBMS

Hibernate - filter Single Column data using date where clause

Lets say One table ABC having two column i.e. ID & CREATED_DATE
I want to fetch those ID which is created lets say '09-11-2017' and '09-17-2017'
Below SQL query working fine but I want to implement same logic using hibernate.
select ID from ABC where between TO_DATE('09-11-2017', 'MM-DD-YYYY') AND TO_DATE('09-17-2017', 'MM-DD-YYYY')
My code is not working.
public List getData(final Date startDate, final Date endDate){
String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
SQLQuery query = getSession().createSQLQuery(sqlString);
query.setParameter(CREATED_DATE);
return query.list();
}
You are missing End date parameter :
query.setParameter(CREATED_DATE, startDate);
query.setParameter(END_DATE, endDate);
It not work because you don't set the correct parameters :
String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
SQLQuery query = getSession().createSQLQuery(sqlString);
query.setParameter("startDate ", start_date);
query.setParameter("endDate", end_date);
return query.list();
The parameters must match the string on the query
Try this:
public List getData(final Date startDate, final Date endDate){
String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
SQLQuery query = getSession().createSQLQuery(sqlString);
query.setParameter("startDate",startDate);
query.setParameter("endDate",endDate);
return query.list();
}
--
pscar13

how to parse date n java to oracle/sql query?

I have a Query like
String query = "Select * from Orders where ordername = ? and orderDate > SYSDATE - 2 ";
i will pass **orderName** and lastDate from UI or some constant ("20-9-2016").
orderDate=SYSDATE - 2 --> instead of "2" i will send lastDate.
Is it correct? SYSDATE oracle function and "2" before constant. now "2" can be user input.
How to write a query in java
String query = "Select * from Orders where ordername = ? and orderDate > SYSDATE - ? ";
Is above query correct ? how to write query
public class CheckOrders extends MappingSqlQuery<Object>{
public PendingOrderExists() {
super(dataSource, queryConfig
.getProperty("query"));
super.declareParameter(new SqlParameter("ORDERNAME", Types.VARCHAR));
//orderdate ? how to declare parameter here
compile();
}
}
for sysdate-?
the ? parameter is to be set object of java.sql.Date class instead of java.util.Date class.
java.sql.Date inherits java.util.Date.
java.sql.Date(long time)
here long is number of milliseconds lapsed since jan1,1979.
GregorianCalendar gc=new GregorianCalendar(2000, 25, 2);
java.util.Date dt=gc.getTime();
long lg=dt.getTime();
java.sql.Date sqldt=new java.sql.Date(lg);
'
pass sqldt object in setDate() method of preparedstatement instance.
hope this works
alkaramansari1#gmail.com

The data types datetime and time are incompatible in the greater than or equal to operator

I have a variable type time in a column of a table of the database.
How can I compare this value in java with this field I mean can i use date, gregoriancalendar?
I've tried adn I still have this message, please can someone give me an advice
Date d2 = new Date(); // timestamp now
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(d2); // set cal to date
cal.set(Calendar.HOUR_OF_DAY, 10); // set hour to midnight
cal.set(Calendar.MINUTE, 30); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millis in second
Date d3 = cal.getTime();
#SuppressWarnings("unchecked")
List<Asistencia> list = (List<Asistencia>) sessionFactory
.getCurrentSession()
.createQuery(
"select new Asistencia( asis.idAsistencia,"
+ "asis.horaInicio, asis.horaFin) "
+ "from Asistencia asis "
+ "where :hour >= asis.horaInicio and :hour <= asis.horaFin")
.setParameter("hour", d3).list();
I also used between
where :hour between asis.horaInicio and asis.horaFin
and the mesage is the same:
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - The data types datetime and time are incompatible in the greater than or equal to operator.
The data types datetime and time are incompatible in the greater than or equal to operator.
Here the class Asistencia:
public class Asistencia implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long idAsistencia;
private Date horaInicio;
private Date horaFin;
private int idAula;
private int idCurso;
private int idPeriodo;
private Date fecha;
public Asistencia (){
}
public Asistencia (long idAsistencia, Date horaInicio, Date horaFin){
this.idAsistencia
this.horaInicio = horaInicio;
this.horaFin = horaFin;
}
}
It seems the only problem was I'm using SQL Server 2008 and is necessary to put sendTimeAsDateTime=false in the connections properties.
Here a similar question.
comparing time in sql server through hibernate
I encountered this error using SpringBoot(v2.2.2) and MSSQL server (jdbc7.4.1) when calling a JpaRepository API passing null dates. This was first version Repository API
#Query(value = "SELECT t FROM MyEntity t WHERE "
+ " AND ( ?3 IS NULL OR ( ?3 IS NOT NULL AND t.fromDate<= ?3 ))"
+ " AND ( ?2 IS NULL OR ( ?2 IS NOT NULL AND t.toDate>= ?2 ))")
List<MyEntity> getMyEntity(LocalDate fromDate, LocalDate toDate);
When calling API with null value for input dates i got the exception:
The data types date and varbinary are incompatible in the less than or equal to operator
I solved with a CAST:
#Query(value = "SELECT t FROM MyEntity t WHERE "
+ " AND ( ?3 IS NULL OR ( ?3 IS NOT NULL AND t.fromDate<= CAST( ?3 AS date ) ))"
+ " AND ( ?2 IS NULL OR ( ?2 IS NOT NULL AND t.toDate>= CAST( ?2 AS date ) ))")
List<MyEntity> getMyEntity(LocalDate fromDate, LocalDate toDate);
Without setting that sendTimeAsDateTime property, which is not available for the SQL Server drivers older than 3.0 (and some of us are stuck with what we have, for reasons), you could try to use a String instead of a date. This worked for me using a PreparedStatement and I bet it would work in this scenario also. Change the last line of your first code block to:
.setParameter( "hour", new SimpleDateFormat("HH:mm:ss.SSS").format(d3) ).list();
I've encountered the same issue when querying data by entity property of type javax.time.LocalDate via spring-data-jpa and eclipselink . Connection setting sendTimeAsDateTime=false didn't help. This was fixed by adding spring-data-jpa converter <class>org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters$LocalDateConverter</class> into the persistence.xml file. Hope this helps.
I also have the same issue. My sql data type is Time(7) and each time I want to compare it via JPQL query, that error comes out. Connection string sendTimeAsDateTime=false didn't work. Adding <class>org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters$LocalDateConverter</class> into the persistence.xml also didn't work.
What I do is, store data Time(7) from sql into String, for example this is my table design on sql
StartTime time(7)
In my java class I store that field into String variable
#Entity
#Table(name = "tableSchedule")
public class TableSchedulue implements Serializable {
private static final long serialVersionUID = -9112498278775770919L;
....
#Column(name = "StartTime")
private String startTime;
.....
}
When I use JPQL query like this (in repository)
#Query(value = "SELECT a "
+ "FROM TableSchedule a "
+ "WHERE a.startTime <= ?1 ")
List<TableSchedulue > getTestData(String startTime);
Your string format must HH:mm:ss
It works. Hope it helps
CONS : Because in SQL the type is Time(7) so value 08:00:00 in SQL will become 08:00:00.0000000 in persistence so you need to parse it into your needs

Hibernate / Java Object can not be converted to a Date

I have the following method in my java. For some reason when I try and cast l_month as a Date it says that the object can not be cast. In my sql statement I convert the date to just be the month using the DATE_FORMAT with '%M', so it just returns a list of month names and the number of logins for that month. How can I get that l_month field to become a Date. Ultimately I am changing it to a string so if it could be cast to a string that would be great also but nothing seems to be working.
public List<Logins> getUserLoginsByMonth() {
Session session = getSessionFactory().openSession();
ArrayList<Logins> loginList = null;
try {
String SQL_QUERY = "SELECT l_date as l_month, SUM(logins) as logins FROM (SELECT DATE_FORMAT(login_time, '%M') as l_date, COUNT(DISTINCT users) as logins FROM user_logins WHERE login_time > DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY DATE(login_time)) AS Z GROUP BY(l_month)";
Query query = session.createSQLQuery(SQL_QUERY)
query.addScalar("l_month")
query.addScalar("logins");
List results = query.list();
for(ListIterator iter = results.listIterator(); iter.hasNext() ) {
Objects[] row = (Object[])iter.next();
System.out.println((Date)row[0}]);
System.out.println((BigInteger)row[1]);
}
}
catch(HibernateException e) {
throw new PersistenceDaoException(e);
}
finally {
session.close();
}
}
DATE_FORMAT is
Blockquote Formats the date value according to the format string.
So it's a string not date.

Categories

Resources