Java.lang.ClassCastException:模型类无法转换为模型类

时间:2018-06-25 09:27:05

标签: java spring-boot

从上面的标题开始,当前我遇到了无法从模型类转换到模型类的问题。我编写的代码是否有问题? 请随时向我询问更多信息。谢谢。

我怀疑:

此方法“ selectTheOldFnException”出现了一些错误,这就是使用了休眠模式,但是我不确定该理论。

REST控制器

    @RequestMapping(value = "/runMatching/{id}", method = RequestMethod.GET, params = "actionRun")
public String runMatching(@PathVariable(required = true, name = "id") long id) {

    System.out.println("the id is: " + id);

            if (fileExist = true) {

                //upload to db
                int uploadDB = dmttDAO.uploadListToDB(filePath);

                try {

                    //int result = matchingEngine.execute();
                    matchingEngine.execute();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            } else {

                break;
            }
        }
    }

    return "redirect:/excpMonitor";

}

使用HIBERNATE选择POJO-MatchingEngine.class

package com.portal.dmtt.match;

import com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception;
import com.portal.dmtt.model.exceptionMonitoring.FN_Result_Set;
import com.portal.dmtt.model.exceptionMonitoring.config.FN_FR_new_Location;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.List;

public class MatchingEngine {

    private final Logger logger = Logger.getLogger(MatchingEngine.class);


    private List<FN_Old_Exception> fnOldExceptionList;

    private List<FN_Result_Set> fnResultSetList;

    private List<FN_FR_new_Location> fnFrNewLocationList;

    private FN_Result_Set theFnResultSet;

    private FN_Old_Exception theFnOldException;

    public int execute() {

        int result = 0;

        System.out.println(">>>>>>>>>>>>>>>>Start Matching Engine<<<<<<<<<<<<<<<< ");

        System.out.println("Start: selectTheOldFnException ");
        result = selectTheOldFnException();
        if (result < 0) {
            logger.error("[Problem method at selectTheOldFnException]. Result: " + result);

            return -1;
        }

        System.out.println("Start: selectTheConfigurationFN ");
       // result = selectTheConfigurationFN();
        if (result < 0) {
            logger.error("[Problem method at selectTheOldFnException]. Result: " + result);

            return -2;
        }

        System.out.println("Start: matchFN ");
        //result = matchFN();
        if (result < 0) {
            logger.error("[Problem method at matchFN]. Result: " + result);

            return -3;
        }

        System.out.println("Start: theFnResultSet ");
        //result = writeItemToDb(theFnResultSet);
        if (result < 0) {
            logger.error("[Problem method at write item to db]. Result: " + result);

            return -4;
        }

        System.out.println("Start: findNewFN ");
        //result = findNewFN();
        if (result < 0) {
            logger.error("[Problem method at findNewFN]. Result: " + result);
            return -5;
        }

        System.out.println(">>>>>>>>>>>>>>>>End Matching Engine<<<<<<<<<<<<<<<< ");

        return result;
    }

    /**
     * Select the old fn Exception
     *
     * @return
     */
    private int selectTheOldFnException() {

        int result = 0;

        // create session factory
        SessionFactory factory = new Configuration().configure("hibcfg.eMonitor.xml").addAnnotatedClass(FN_Old_Exception.class).buildSessionFactory();

        // create a session
        Session session = factory.openSession();

        try {
            String Query1 = "from FN_Old_Exception";

            // start a transaction
            session.beginTransaction();

            // query current reported watch list
            fnOldExceptionList = session.createQuery(Query1).list();

            // commit transaction
            session.getTransaction().commit();

            result = fnOldExceptionList.size();

            //System.out.println(fnOldExceptionList.toString());

            for (int i = 0; i < result; i++) {

                System.out.println("selectTheOldFnException ---->>>" + fnOldExceptionList.get(i).toString());
            }

        } catch (SessionException e) {

            logger.fatal("Select selectFnException_New: Caught an Exception" + e.getMessage());

        } finally {

            session.close();
            factory.close();

        }

        return result;

    }

    /**
     * match FN based on parameter
     *
     * @return
     */
    private int matchFN() {

        int result = 0;

        result = fnOldExceptionList.size();
        int sizeFNConfiguration = fnFrNewLocationList.size();

        for (int j = 0; j < sizeFNConfiguration; j++) {

            String matchSpId = fnFrNewLocationList.get(j).getMatch_SP_Id();
            String matchLocId = fnFrNewLocationList.get(j).getMatch_Loc_Id();
            String remarks = fnFrNewLocationList.get(j).getRemarks();


            theFnOldException = new FN_Old_Exception();

            for (int i = 0; i < result; i++) {

                if (((fnOldExceptionList.get(i).getSp_Id().equals(matchSpId))) && ((fnOldExceptionList.get(i).getLoc_Id().equals(matchLocId)))) {

                    // set the new remarks after hit the logic
                    fnOldExceptionList.get(i).setRemarks(remarks);

                    String spId = fnOldExceptionList.get(i).getSp_Id();
                    String locId = fnOldExceptionList.get(i).getLoc_Id();
                    String status = fnOldExceptionList.get(i).getXfer_Xmit_Status();
                    String fileName = fnOldExceptionList.get(i).getXfer_File_Name();
                    String updateTS = fnOldExceptionList.get(i).getUpdate_Ts();
                    String yymm = fnOldExceptionList.get(i).getYYMM();
                    String Remarks = fnOldExceptionList.get(i).getRemarks();

                    //display message
                    //System.out.println("matchFN --->>>" + fnOldExceptionList.get(i).toString());

                    theFnResultSet = new FN_Result_Set(spId, locId, status, fileName, updateTS, yymm, Remarks);

                    writeItemToDb(theFnResultSet);
                }
            }
        }

        return result;
    }

    /**
     * SAVE-
     * all result to the new table (FN_Result_Set)
     *
     * @return
     */
    public int writeItemToDb(FN_Result_Set fn_result_set) {

        int result = 0;

        // create session factory
        SessionFactory factory = new Configuration().configure("hibcfg.eMonitor.xml").addAnnotatedClass(FN_Result_Set.class).buildSessionFactory();
        // create a session
        Session session = factory.openSession();

        try {

            session.beginTransaction();

            session.saveOrUpdate(fn_result_set);

            session.getTransaction().commit();

        } catch (HibernateException ex1) {
            ex1.printStackTrace();

        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {

            session.close();
            factory.close();

        }

        return result;
    }

    /**
     * differentiate between two entity
     *
     * @return
     */
    private int findNewFN() {

        int result = 0;

        result = fnOldExceptionList.size();

        for (int i = 0; i < result; i++) {

            if (fnOldExceptionList.get(i).getRemarks() == null) {

                String spId = fnOldExceptionList.get(i).getSp_Id();
                String locId = fnOldExceptionList.get(i).getLoc_Id();
                String status = fnOldExceptionList.get(i).getXfer_Xmit_Status();
                String fileName = fnOldExceptionList.get(i).getXfer_File_Name();
                String updateTS = fnOldExceptionList.get(i).getUpdate_Ts();
                String yymm = fnOldExceptionList.get(i).getYYMM();
                String Remarks = "New Location";

                theFnResultSet = new FN_Result_Set(spId, locId, status, fileName, updateTS, yymm, Remarks);

                writeItemToDb(theFnResultSet);

            }
        }

        return result;
    }

    /**
     * select the configuration selected FN from database
     *
     * @return
     */
    private int selectTheConfigurationFN() {


        int result = 0;

        // create session factory
        SessionFactory factory = new Configuration().configure("hibcfg.eMonitor.xml").addAnnotatedClass(FN_FR_new_Location.class).buildSessionFactory();

        // create a session
        Session session = factory.openSession();

        try {
            String Query1 = "from FN_FR_new_Location";

            // start a transaction
            session.beginTransaction();

            // query current reported watch list
            fnFrNewLocationList = session.createQuery(Query1).list();

            // commit transaction
            session.getTransaction().commit();

            result = fnFrNewLocationList.size();

            //System.out.println(fnOldExceptionList.toString());

            for (int i = 0; i < result; i++) {

                System.out.println("selectTheOldFnException ---->>>" + fnFrNewLocationList.get(i).toString());
            }

        } catch (SessionException e) {

            logger.fatal("Select fnFrNewLocationList : Caught an Exception" + e.getMessage());

        } finally {

            session.close();
            factory.close();

        }

        return result;

    }

}

POJO CLASS

package com.portal.dmtt.model.exceptionMonitoring;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "fn_old_exception")
public class FN_Old_Exception {

    @Id
    @Column(name = "id")
    private int Id;

    @Column(name = "Sp_Id")
    private String Sp_Id;

    @Column(name = "Loc_Id")
    private String Loc_Id;

    @Column(name = "Xfer_Xmit_Status")
    private String Xfer_Xmit_Status;

    @Column(name = "Xfer_File_Name")
    private String Xfer_File_Name;

    @Column(name = "Update_Ts")
    private String Update_Ts;

    @Column(name = "YYMM")
    private String YYMM;

    @Column(name = "Remarks")
    private String Remarks;

例外代码

java.lang.ClassCastException: com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception cannot be cast to com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception
at com.portal.dmtt.match.MatchingEngine.selectTheOldFnException(MatchingEngine.java:125)
at com.portal.dmtt.match.MatchingEngine.execute(MatchingEngine.java:49)
at com.portal.dmtt.match.MatchingEngine.finalExecution(MatchingEngine.java:37)
at com.portal.dmtt.controller.ExcpMonitorController.runMatching(ExcpMonitorController.java:236)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

2 个答案:

答案 0 :(得分:0)

贷给 @AndyWilkinson

禁用SpringBoot开发工具:

<!--
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
-->

答案 1 :(得分:0)

这里您正在使用2个同名FN_Old_Exception的不同类

这两个类放在相同的包中的不同jar文件中

com.portal.dmtt.model.exceptionMonitoring.FN_Old_Exception 

需要查看完整的代码库来解决该冲突,您可以分享吗?