1

The DB persist java.util.date and i need a query to get all the data between 2 Dates with only using java.util.date. I use the JPA 2.1

String sql = "SELECT * FROM table WHERE created > '"+date1+"' AND created < '"+date2+"'";

This query provides always a List with 0 elements

1
  • Can you try: Query q = em.createQuery("Select m from table m " + "where m.created > :date1 and m.created < :date2"); q.setParameter("date1", date1); q.setParameter("date2", date2); List<Message> results = (List<Message>) q.getResultList(); Commented May 25, 2016 at 12:44

1 Answer 1

3

The problem is that your dates are being added to the SQL query as string values. The database is getting something like:

String sql = "SELECT * FROM table WHERE created > 'Wed May 25 14:33:18 SAST 2016' and created < 'Wed May 25 14:33:18 SAST 2016'";

The database is seeing it as a string and that explains why it isn't working.

The single best way to resolve it is use bind variables::

String sql = ""SELECT * FROM table WHERE created > ? AND created < ?"
//Create the query object using that SQL string, then set values
sqlQuery.setParameter(1, date1);
sqlQuery.setParameter(2, date2);

Then execute the prepared statement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.