Hibernate / Java Object can not be converted to a Date - java

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.

Related

TimeStamp Difference Between Java and SQLite

Hello I have and SLQLite database in which I have table water_logs
CREATE TABLE water_logs(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
amount REAL NOT NULL,
icon INTEGER NOT NULL,
date INTEGER NOT NULL);
I store date in milliseconds.
Calendar cal = Calendar.getInstance();
cal.getTimeInMillis();
My problem is I want to get the day from the my date column using strftime function. The problem is tjat java calendar timestamp is different from SLQLite time stamp
1436859563832 --> result from cal.getTimeInMillis();
1436607407--> SELECT strftime('%s','now')
What I'm actually trying to do is to group records by day. The following SQL query works just fine if value of SELECT strftime('%s','now') is paste in the date column
SELECT SUM(amount), date(`date`) FROM water_logs
GROUP BY date(`date`, 'unixepoch')
Seems to me that you are using 2 different value types.
When you use
Calendar cal = Calendar.getInstance();
long time = cal.getTimeInMillis();
The output value is in Milliseconds, as described here.
While when you use
strftime('%s','now')
The output value is in Seconds, as described here.
So, that might be the cause for the mismatch between the two values.
Of course that the value in seconds might undergo some rounding which might change its value a little.
I will try to provide you the best way to store Dates in SQLite database.
1) Always use integers to store the dates.
2) Use this utility method to store the dates into the database,
public static Long saveDate(Date date) {
if (date != null) {
return date.getTime();
}
return null;
}
Like,
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, saveDate(entity.getDate()));
long id = db.insertOrThrow(TABLE_NAME, null, values);
3) Use this utility method to load date,
public static Date loadDate(Cursor cursor, int index) {
if (cursor.isNull(index)) {
return null;
}
return new Date(cursor.getLong(index));
}
like,
entity.setDate(loadDate(cursor, INDEX));
4) You can also order the data by date using simple ORDER clause,
public static final String QUERY = "SELECT table._id, table.dateCol FROM table ORDER BY table.dateCol DESC";
//...
Cursor cursor = rawQuery(QUERY, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// Process results
}

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

How to get date value from SQLite in java

I have a simple table in my database:
CREATE TABLE [InformacjeZDziekanatu] (
[_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[DataWstawienia] DATE NOT NULL,
[DataModyfikacji] DATE NOT NULL,
[Tresc] VARCHAR2 NOT NULL);
In my application only what I want to do is to get value of DataWstawienia column.
I am using such method:
try {
ResultSet result = stat.executeQuery("select * from InformacjeZDziekanatu order by _id desc limit 5");
int id;
Date dataWst;
Date dataMod;
String tresc;
for(int j = 0 ; j < 5 ; j++) {
result.next();
Object[] lista = new Object[4];
id = result.getInt("_id");
dataWst = result.getDate("DataWstawienia");
dataMod = result.getDate("DataModyfikacji");
tresc = result.getString("Tresc");
lista[0] = id;
lista[1] = dataWst;
lista[2] = dataMod;
lista[3] = tresc;
dane[j] = lista;
}
}
All dates in DataWstawienia column are today's dates but using this method above I get 1970-01-01 date all the time.
What did I do wrong?
SQLIte does not have a DATE data type. Dates need to either be stored as integers (number of seconds since Unix Epoch is common) or as ISO 8601 times (e.g. 2013-10-01T12:12:12). If you say DATE in your SQLite schema you will store values as strings. Your solution of changing the type of dateWst to String acknowledges the fact that you are storing dates as strings and not as an internal date type.

Doing a query for each day in a period, turning it into one query

I have this:
public Map<Day,Integer> getUniqueLogins(long fromTime, long toTime) {
EntityManager em = emf.createEntityManager();
try {
Map<Day,Integer> resultMap = new ...;
for (Day day : daysInPeriod(fromTime, toTime)) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> q = cb.createQuery(Long.class);
// FROM UserSession
Root<UserSession> userSess = q.from(UserSession.class);
// SELECT COUNT(DISTINCT userId)
q.select(cb.countDistinct(userSess.<Long>get("userId")));
// WHERE loginTime BETWEEN ...
q.where(cb.between(userSess.<Date>get("loginTime"), day.startDate(), day.endDate()));
long result = em.createQuery(q).getSingleResult();
resultMap.put(day, (int) result);
}
return resultMap;
} finally {
em.close();
}
}
This executes a query for each day in a given period (the period being in the order of magnitude of a month).
Could I get this specific data in one query? I'm using Hibernate/MySQL, but I'd prefer not to need any non-standard functions.
Assuming your original query is:
SELECT COUNT(DISTINCT userId)
FROM UserSession
WHERE loginTime BETWEEN dayStart AND dayEnd;
This should return the same results as running the original one per each day of the period:
SELECT date(loginTime) AS day, COUNT(DISTINCT userId)
FROM UserSession
WHERE loginTime BETWEEN startDate AND endDate
GROUP BY day;
GROUP BY the date segment of LoginTime counting distinct userids. The back-end should provide a way to extract the date-part of the datetime value.
You'll have to use MySQL specific functions to do this.
SELECT FROM_DAYS(TO_DAYS(loginTime)) AS day, COUNT(DISTINCT userId)
FROM UserSession
WHERE loginTime BETWEEN :fromTime AND :toTime
GROUP BY day
The from_days/to_days will convert the loginTime to a number of days and then back to a datetime but with the hour/minute/second parts zero'd.

Filtering records in app-engine (Java)

I have following code running perfectly. It filter records based on single parameter.
public List<Orders> GetOrders(String email)
{
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Orders.class);
query.setFilter("Email == pEmail");
query.setOrdering("Id desc");
query.declareParameters("String pEmail");
query.setRange(0,50);
return (List<Orders>) query.execute(email);
}
Now i want to filter on multiple parameters. sdate and edate is Start Date and End Date.
In datastore it is saved as Date (not String).
public List<Orders> GetOrders(String email,String icode,String sdate, String edate)
{
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Orders.class);
query.setFilter("Email == pEmail");
query.setFilter("ItemCode == pItemCode");
query.declareParameters("String pEmail");
query.declareParameters("String pItemCode");
.....//Set filter and declare other 2 parameters
.....//
......
query.setRange(0,50);
query.setOrdering("Id desc");
return (List<Orders>) query.execute(email,icode,sdate,edate);
}
Any clue?
My first problem is solved. But still have some problem
1: How I can filter by Date parameter (Getting as string in jsp) ?
2: The query.execute() method support upto 3 parameters. Is it possible to pass more?
You can't use multiple SetFilter() to setup multiple conditions. You must use a single if-like condition, so it will be
query.setFilter("Email == pEmail && ItemCode == pItemCode");
same for declareParameters with a comma-separeted list as follows
Query.declareParameters("String pEmail, String pItemCode");

Categories

Resources