java.lang.ClassCastException: String can't be cast to Date

心不动则不痛 提交于 2020-02-01 06:56:25

问题


Stacktrace:

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
        at org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor.unwrap(JdbcTimestampTypeDescriptor.java:41)
        at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$1.doBind(TimestampTypeDescriptor.java:65)
        at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:90)
        at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
        at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:281)
        at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
        at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:613)
        at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
        at org.hibernate.loader.Loader.doQuery(Loader.java:909)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
        at org.hibernate.loader.Loader.doList(Loader.java:2553)
        at org.hibernate.loader.Loader.doList(Loader.java:2539)
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
        at org.hibernate.loader.Loader.list(Loader.java:2364)
        at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
        at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
        at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
        at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
        at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
        at com.nutsaboutcandywebproject.dao.SQLOrdersDataAccess.getMonthlyReport(SQLOrdersDataAccess.java:129)
        at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getOrdersPerMonth(ServiceFacadeImpl.java:127)
        at com.nutsaboutcandywebproject.controller.OrderController.orderHistory(OrderController.java:237)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:724)

Code:

@Override
    public List <Orders> getMonthlyReport(String date){

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        String hqlQuery = "FROM Orders WHERE orderDate LIKE :orderDate AND orderStatus = :orderStatus";
        Query query = session.createQuery(hqlQuery);
        query.setParameter("orderDate", date+"%");
        query.setParameter("orderStatus", "PENDING");

        List<Orders> orderList = query.list();

        transaction.commit();
        session.close();
        return orderList;
    }

回答1:


Thanks guys for all the help. I managed to solve this problem with the aid of your answers here. So this is what I've done to make it work according to the purpose.

@Override
    public List <Orders> getMonthlyReport(String date){

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

           DateFormat sdf = new SimpleDateFormat("yyyy-mm");
           Date startDate = null;
        try {
            startDate = sdf.parse(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



        String hqlQuery = "FROM Orders WHERE orderDate LIKE CONCAT(:fromDate,'%') AND orderStatus = :orderStatus";

        Query query = session.createQuery(hqlQuery);
        query.setParameter("fromDate", sdf.format(startDate));
        query.setParameter("orderStatus", "PENDING");


        List<Orders> orderList = query.list();

        transaction.commit();
        session.close();
        return orderList;
    }



回答2:


Its probably because in your Orders entity, the orderDate field is type of java.util.Date and you're passing a String in your query. Change method signature from this:

public List <Orders> getMonthlyReport(String date)

to this:

public List <Orders> getMonthlyReport(Date date)

and resolve compile errors. If you would have troubles with converting String to Date, use i.e. standard java utility class: SimpleDateFormat http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.




回答3:


Use a dateFormat class to convert String to date and then set it in your query.

Say,your date is in format 10/31/2013,you can do like this

   String val ="31/10/2013";
   DateFormat sdf = new SimpleDateFormat("mm/dd/yyy");
   Date startDate = sdf.parse(val);

   Calendar cal = Calendar.getInstance();  
   cal.setTime(startDate);  
   cal.set(Calendar.MONTH, (cal.get(Calendar.MONTH)+1));  
   Date endDate = cal.getTime();

    String hqlQuery = "FROM Orders WHERE orderDate BETWEEN :fromDate and :toDate  AND orderStatus = :orderStatus";

    Query query = session.createQuery(hqlQuery);
    query.setParameter("fromDate", startDate );
    query.setParameter("toDate", startDate );
    query.setParameter("orderStatus", "PENDING");


来源:https://stackoverflow.com/questions/22590036/java-lang-classcastexception-string-cant-be-cast-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!