当前位置: 首页 > 面试题库 >

接收org.hibernate.TypeMismatchException异常

康秋月
2023-03-14
问题内容

我正在使用SpringMVC在带有Spring的应用程序上工作,遇到以下错误,我不知道如何处理。

现在我在控制台中收到此消息:

org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.Integer, got class java.lang.String
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:86)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878)
at org.hibernate.impl.SessionImpl.load(SessionImpl.java:795)
at org.hibernate.impl.SessionImpl.load(SessionImpl.java:788)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
at com.sun.proxy.$Proxy11.load(Unknown Source)
at com.my.dao.DepartementImplDB.getDepartementByNom(DepartementImplDB.java:54)
at com.my.dao.DepartementImplDB.addDepartement(DepartementImplDB.java:29)
at com.my.service.DepartementImplMetier.create(DepartementImplMetier.java:57)
at com.my.controller.ImportController.Read(ImportController.java:279)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

这是我的ImportController类

/**
 * @author Ilias
 */
package com.my.controller;

//import ...

import com.my.dao.Departement;

@Controller
public class ImportController {


DepartementImplMetier dbD = new DepartementImplMetier();


@RequestMapping(value="/read")
public String Read(Model model,@RequestParam CommonsMultipartFile[] fileUpload) 
        throws IOException, EncryptedDocumentException, InvalidFormatException, java.text.ParseException
{


    liste = extraire(modelnom);

for(int m=0, i=29;i<liste.size();i=i+29){//i=i+29

     Employe employe= new Employe();
     Departement departement = new Departement();

    if(i % 29 == 0) m++;

    //...  Some code here

        String dep = (String)liste.get(29*m+13).toString();

        Departement d = new Departement();
        departement.setNomDepartement(dep);


        boolean bool=true;
        List<Departement> departements = dbD.getAll();


        boolean depbool = true;
        for(int j=0;j< departements.size();j++){
            if(departements.get(j).getNomDepartement() ==  dep )
            {
                depbool = false;
            }

            if(depbool){
            try {
                dbD.create(departement);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        }

        for(int n=0;n<employes.size();n++){
            if(employes.get(n).getMatriculeMY() ==  (int)mat )
            {
                bool= false;
            }
        }
        if(bool){

        try {
            dbD.create(departement);
            dbE.create(employe);

        } catch (Throwable e) {
            e.printStackTrace();
        }

        }

    }
}
return "redirect";
}}
}

这是我的Employe.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 5 ao?t 2015 11:05:44 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.my.dao.Employe" table="EMPLOYE">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="nomEmploye" type="java.lang.String">
            <column name="NOMEMPLOYE" />
        </property>
        <property name="prenomEmploye" type="java.lang.String">
            <column name="PRENOMEMPLOYE" />
        </property>
        <property name="matriculeMY" type="int">
            <column name="MATRICULEMY" />
        </property>
        <property name="adresse" type="java.lang.String">
            <column name="ADRESSE" />
        </property>
        <property name="sexe" type="java.lang.String">
            <column name="SEXE" />
        </property>
        <property name="cin" type="java.lang.String">
            <column name="CIN" />
        </property>
        <property name="dateNaissance" type="java.lang.String">
            <column name="DATENAISSANCE" />
        </property>
        <property name="situationFamiliale" type="java.lang.String">
            <column name="SITUATIONFAMILIALE" />
        </property>
        <property name="dateEntree" type="java.lang.String">
            <column name="DATEENTREE" />
        </property>
        <property name="dateSortie" type="java.lang.String">
            <column name="DATESORTIE" />
        </property>
        <property name="numCIMR" type="java.lang.String">
            <column name="NUMCIMR" />
        </property>
        <property name="numCNSS" type="java.lang.String">
            <column name="NUMCNSS" />
        </property>
        <property name="numMUT" type="java.lang.String">
            <column name="NUMMUT" />
        </property>
        <property name="profile" type="java.lang.String">
            <column name="PROFILE" />
        </property>
        <property name="resteConge" type="java.lang.String">
            <column name="RESTECONGE" />
        </property>
        <property name="banque" type="java.lang.String">
            <column name="BANQUE" />
        </property>
        <property name="numCpteBanc" type="java.lang.String">
            <column name="NUMCPTEBANC" />
        </property>
        <!-- <property name="fonction" type="java.lang.String">
            <column name="FONCTION" />
        </property> -->
        <property name="salaire" type="float">
            <column name="SALAIRE" />
        </property>
        <property name="indTransport" type="float">
            <column name="INDTRANSPORT" />
        </property>
        <property name="indRepresent" type="float">
            <column name="INDREPRESENT" />
        </property>
        <property name="indPanier" type="float">
            <column name="INDPANIER" />
        </property>
        <many-to-one name="eDepartement" class="com.my.dao.Departement" access="field" fetch="join">
            <column name="EDEPARTEMENT" />
        </many-to-one>
        <many-to-one name="eFonction" class="com.my.dao.Fonction" access="field" fetch="join">
            <column name="EFONCTION" />
        </many-to-one>
        <many-to-one name="eService" class="com.my.dao.Service" access="field" fetch="join">
            <column name="ESERVICE" />
        </many-to-one>
        <many-to-one name="eTypePaiement" class="com.my.dao.TypePaiement" access="field" fetch="join">
            <column name="ETYPEPAIEMENT" />
        </many-to-one>
        <many-to-one name="eModePaiement" class="com.my.dao.ModePaiement" access="field" fetch="join">
            <column name="EMODEPAIEMENT" />
        </many-to-one>
    </class>
</hibernate-mapping>

这是我的Departement.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 5 ao?t 2015 11:05:44 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.my.dao.Departement" table="DEPARTEMENT">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="nomDepartement" type="java.lang.String">
            <column name="NOMDEPARTEMENT" />
        </property>
        <set name="Employe" inverse="true">
            <key column="ID" not-null="true"/>
            <one-to-many class="com.my.dao.Employe" />
        </set>
    </class>
</hibernate-mapping>

调试后,问题出在这里:

boolean depbool = true;
        for(int j=0;j< departements.size();j++){
            if(departements.get(j).getNomDepartement() ==  dep )
            {
                depbool = false;
            }

            if(depbool){
            try {
                dbD.create(departement);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        }

恰好在这里:

dbD.create(departement);

这个DepartementImplDB类

package com.my.dao;

import java.util.List;
import org.hibernate.Session;
import com.my.util.HibernateUtil;

/**
 * @author Ilias
 *
 */
public class DepartementImplDB implements DepartementDao {

    /**
     * @see com.my.dao.DepartementDao#addDepartement(com.my.dao.Departement)
     */
    @Override
    public int addDepartement(Departement D) {
        // TODO Auto-generated method stub

        Session session =  HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
        session.beginTransaction();System.out.println("********");
        session.save(D);System.out.println("departement implement metier");
        session.getTransaction().commit();
        D=this.getDepartementByNom(D.getNomDepartement());
        return D.getId();
    }

    /**
     * @see com.my.dao.DepartementDao#getDepartementById(int)
     */
    @Override
    public Departement getDepartementById(int id) {
        // TODO Auto-generated method stub

        Session session =  HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Departement dept = (Departement) session.load(Departement.class, id);
        return dept;
    }

    /**
     * @see com.my.dao.DepartementDao#getDepartementByNom(java.lang.String)
     */
    @Override
    public Departement getDepartementByNom(String nomDepartement) {
        // TODO Auto-generated method stub
        Session session =  HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Departement dept = (Departement) session.load(Departement.class, nomDepartement);
        return dept;
    }

    /**
     * @see com.my.dao.DepartementDao#deleteDepartement(int)
     */
    @Override
    public void deleteDepartement(int id) {
        // TODO Auto-generated method stub
        Session session =  HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Departement dept = (Departement) session.load(Departement.class, id);
        session.delete(dept);
        session.getTransaction().commit();
    }

    /**
     * @see com.my.dao.DepartementDao#updateDepartement(com.my.dao.Departement)
     */
    @Override
    public void updateDepartement(Departement D) {
        // TODO Auto-generated method stub
    }

    /**
     * @see com.my.dao.DepartementDao#getAllDepartement()
     */
    @Override
    public List<Departement> getAllDepartement() {
        // TODO Auto-generated method stub

        Session session =  HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
        session.beginTransaction();
        return session.createQuery("from Departement").list();          
    }
}

可以提供帮助吗?


问题答案:

你的错误是

org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.Integer, got class java.lang.String

在您的堆栈跟踪中,我们可以看到dbd.create调用了其他方法

    at com.my.dao.DepartementImplDB.getDepartementByNom(DepartementImplDB.java:54)
at com.my.dao.DepartementImplDB.addDepartement(DepartementImplDB.java:29)

用你的方法

public Departement getDepartementByNom(String nomDepartement)

您尝试加载具有名称的部门,但您使用由ID加载的session.load wich加载。

 Departement dept = (Departement) session.load(Departement.class, nomDepartement);

您必须提出一个Criteria请求才能按名称加载。喜欢

session.beginTransaction();
Criteria criteria = session.createCriteria(Departement.class);
criteria.add(Restrictions.eq("nomDepartement", nomDepartement).ignoreCase());

 result = (Departement) criteria.uniqueResult();
 session.getTransaction().commit();

ps:在getDepartementById和getDepartementByNom中,您永远不会结束交易。请使用以下模式:

 try {
        session.beginTransaction();

        // your code

        session.getTransaction().commit();
    } catch (HibernateException e) {
        LOGGER.error(e);
        if (session.getTransaction().isActive()) {
            session.getTransaction().rollback();
        }
    }


 类似资料:
  • 我使用jax-ws 2.2.7来生成web服务。操作签名是: TKS!!!

  • 问题内容: 假设我们在C中有一个使用sleep()函数的程序 该程序执行并进入睡眠状态。然后,我们输入+ 将SIGINT信号发送到该进程。 我们知道接收到SIGINT时的默认操作是终止该进程,我们也知道每当睡眠进程收到信号时,sleep()函数都会恢复该进程。 我的教科书上说,为了允许sleep()函数返回,我们必须安装一个SIGINT处理程序,如下所示: 虽然代码看起来很简单,但是如果我想更深入

  • 我有一个应用程序,它使用AlarmManager为用户通知安排警报。我将报警对象的一个实例传递给AlarmManager使用的PendingEvent: 发生报警时间时,my AlarmBroadcastReceiver(我的AlarmBroadcastReceiver(报警广播接收器))正确接收广播,但LogCat警告未找到报警类: 然而,BroadcastReceiver成功地从接收到的意图中

  • 问题内容: 我有两张地图: 我需要接收这些地图之间的差异。是否存在可能是apache utils如何获得此差异?现在看来,需要获取每个映射的条目集,并找到diff1 = set1-set2和diff2 = set2- set1。创建摘要映射后= diff1 + diff2看起来很尴尬。是否存在其他方式?谢谢。 问题答案: 如何谷歌番石榴?

  • 当使用JMeter/Blazemeter运行测试时,我在测试开始后10-20分钟的某个时间段内随机收到以下错误。 < li >非HTTP响应代码:org . Apache . HTTP . conn . httphostconnectexception < li>500内部服务器错误 < li >非HTTP响应代码:org . Apache . HTTP . truncatedchunkexcep

  • 问题内容: 我最近正在研究虹膜框架。在实现处理程序时遇到一个问题。如下所示: 为了使用此控制器,我实现了以下输入脚本: 但是,当我编译代码时,收到以下错误消息: 在我将声明更改为: 然后,编译器通过,没有任何抱怨。 问题是:我认为以下语句是相等的,因为GO编译器将在表下进行转换: 为什么我不能用作为参数,而不是作为参数传递给? 感谢您的宝贵时间和分享。 问题答案: 参阅文件: 类型可能具有与之关联