Convert String to "yyy-MM-dd" format with Date as data type

Lenita Quejado :

I'm trying to get the data stored in database by getting the date then populate the table.

    List<String> contents = new ArrayList<>();
    List<Record> records

try {
        Session session = sessionFactory.getCurrentSession();
        Query<World> query = null;

        query = session.createQuery("from World where date like :dateCont, World.class);
        query.setParameter("dateCont", "%" + contents.get(0) + "%");

        worlds = query.getResultList();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

The problem here is that it gives me an error exception:

java.lang.ClassCastException: class java.lang.String cannot be cast to class java.util.Date (java.lang.String and java.util.Date are in module java.base of loader 'bootstrap')

I know what's wrong because the List<String> contents values are string and needed to be converted to Date but I tried so many codes and it doesn't work.

//The following are the codes that I tried but it won't work:

//FIRST

 Date date = new SimpleDateFormat("MM/dd/yyyy").parse(contentsStart.get(0));
 new SimpleDateFormat("yyyy-MM-dd").format(date);

//---------------------------------------

//SECOND

Date newDate;
DateFormat formatter = null;

formatter = new SimpleDateFormat("yyyy-MM-dd");
newDate = (Date) formatter.parse(contentsStart.get(0));

So, is there any way to change the given value to date but it should retains the format "yyyy-MM-dd" and the datatype should be Date.

PS: the format of date in database is "yyyy-MM-dd" also. Both my date entity field and date from DB is both Date as their datatype.

Boris Brodski :

You can use like operator only on string (VARCHAR) fields. In the WHERE clause you have to convert your field to string (using format function) in order to be able to use LIKE. So you have to call the convert function (also) IN THE QUERY.

Unfortunately, there are no DATE-functions in EJBQL, so you will have to switch to the native query. For example, for Oracle you can use TO_CHAR like this

SELECT ... WHERE TO_CHAR(date, 'MM/DD/YYYY') LIKE ...

For good performance you will have to add a functional index.

See also http://www.sqlines.com/oracle-to-sql-server/to_char_datetime


One alternative would be to add a new string column date_string, that will contain the formatted representation of your date and use this column with LIKE. But you will have to make absolutely sure, that both dates are always synchronized.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309909&siteId=1