免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3516 | 回复: 7
打印 上一主题 下一主题

hibernate取数据出异常!!! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-04-02 12:36 |只看该作者 |倒序浏览
我想要从数据库中获取到用户的ID所以当用户在登陆的时候去获取.我就用了如下代码:
    public Customer findByName(String custName) {
        log.debug("getting Customer instance with custName: " + custName);
        try {
            Customer instance = (Customer) getHibernateTemplate()
                    .get("org.xqm.db.Customer", custName);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

在Action中
                   try{
Customer c = custdao.findByName(loginForm.getCustName());
System.out.println(c.getCustomerId()+loginForm.getCustName());}
                catch(Exception e){
                        e.printStackTrace();
                }

老是报异常
ERROR - get failed
java.lang.ClassCastException: java.lang.String
        at org.hibernate.type.IntegerType.set(IntegerType.java:39)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:62)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:44)
        at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1115)
        at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1177)
        at org.hibernate.loader.Loader.doQuery(Loader.java:390)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:21
        at org.hibernate.loader.Loader.loadEntity(Loader.java:1345)
        at org.hibernate.loader.entity.EntityLoader.load(EntityLoader.java:116)
        at org.hibernate.loader.entity.EntityLoader.load(EntityLoader.java:101)
        at org.hibernate.persister.entity.BasicEntityPersister.load(BasicEntityPersister.java:2471)
        at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:351)
        at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:332)
        at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:113)
        at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:167)
        at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:79)
        at org.hibernate.impl.SessionImpl.get(SessionImpl.java:621)
        at org.springframework.orm.hibernate3.HibernateTemplate$2.doInHibernate(HibernateTemplate.java:471)
        at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:366)
        at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:465)
        at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:459)
        at org.xqm.db.CustomerDAO.findByName(CustomerDAO.java:67)
        at org.xqm.struts.action.LoginAction.execute(LoginAction.java:46)
        at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106)
        at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
        at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:19
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:11
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
        at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
        at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
        at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
        at java.lang.Thread.run(Thread.java:595)
java.lang.ClassCastException: java.lang.String
        at org.hibernate.type.IntegerType.set(IntegerType.java:39)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:62)
        at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:44)
        at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1115)
        at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1177)
        at org.hibernate.loader.Loader.doQuery(Loader.java:390)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:21
        at org.hibernate.loader.Loader.loadEntity(Loader.java:1345)
        at org.hibernate.loader.entity.EntityLoader.load(EntityLoader.java:116)
        at org.hibernate.loader.entity.EntityLoader.load(EntityLoader.java:101)
        at org.hibernate.persister.entity.BasicEntityPersister.load(BasicEntityPersister.java:2471)
        at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:351)
        at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:332)
        at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:113)
        at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:167)
        at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:79)
        at org.hibernate.impl.SessionImpl.get(SessionImpl.java:621)
        at org.springframework.orm.hibernate3.HibernateTemplate$2.doInHibernate(HibernateTemplate.java:471)
        at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:366)
        at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:465)
        at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:459)
        at org.xqm.db.CustomerDAO.findByName(CustomerDAO.java:67)
        at org.xqm.struts.action.LoginAction.execute(LoginAction.java:46)
        at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106)
        at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
        at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:19
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:11
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
        at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
        at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
        at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
        at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
        at java.lang.Thread.run(Thread.java:595)

这是为什么呢...在线等哦...有没有高手教我下....

论坛徽章:
0
2 [报告]
发表于 2007-04-02 13:07 |只看该作者
看样子,Customer的主键是Integer类型,但你传了一个String去获得

论坛徽章:
0
3 [报告]
发表于 2007-04-02 13:08 |只看该作者
但是我是按名字去找的呀...那怎么能是Integer类型的呢...那我要怎么办呢?

论坛徽章:
0
4 [报告]
发表于 2007-04-02 13:26 |只看该作者
看看对应 Customer   的表,还有对应 xml 配置文件
或贴出来,大家帮看看

论坛徽章:
0
5 [报告]
发表于 2007-04-02 13:36 |只看该作者
好...

Customer.java:

package org.xqm.db;

import org.apache.struts.validator.ValidatorActionForm;



/**
* Customer generated by MyEclipse - Hibernate Tools
*/

public class Customer extends ValidatorActionForm implements java.io.Serializable {


    // Fields   

     private Integer customerId;
     private String custName;
     private String password;
     private String email;


    // Constructors

    /** default constructor */
    public Customer() {
    }

   
    /** full constructor */
    public Customer(String custName, String password, String email) {
        this.custName = custName;
        this.password = password;
        this.email = email;
    }

   
    // Property accessors

    public Integer getCustomerId() {
        return this.customerId;
    }
   
    public void setCustomerId(Integer customerId) {
        this.customerId = customerId;
    }

    public String getCustName() {
        return this.custName;
    }
   
    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getPassword() {
        return this.password;
    }
   
    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return this.email;
    }
   
    public void setEmail(String email) {
        this.email = email;
    }

}


Customer.hmb.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">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    <class name="org.xqm.db.Customer" table="customer">
        <id name="customerId" type="java.lang.Integer">
            <column name="customer_id" />
            <generator class="native" />
        </id>
        <property name="custName" type="java.lang.String">
            <column name="cust_name" length="100" not-null="true" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="100" not-null="true" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="email" length="100" not-null="true" />
        </property>
    </class>
</hibernate-mapping>


CustomerDAO.java

package org.xqm.db;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
* Data access object (DAO) for domain model class Customer.
* @see org.xqm.db.Customer
* @author MyEclipse - Hibernate Tools
*/
public class CustomerDAO extends HibernateDaoSupport {

    private static final Log log = LogFactory.getLog(CustomerDAO.class);

        //property constants
        public static final String CUST_NAME = "custName";
        public static final String PASSWORD = "password";
        public static final String EMAIL = "email";

        protected void initDao() {
                //do nothing
        }
   
    public void save(Customer transientInstance) {
        log.debug("saving Customer instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
   
        public void delete(Customer persistentInstance) {
        log.debug("deleting Customer instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
   
    public Customer findById( java.lang.Integer id) {
        log.debug("getting Customer instance with id: " + id);
        try {
            Customer instance = (Customer) getHibernateTemplate()
                    .get("org.xqm.db.Customer", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
   
    public Customer findByName(String custName) {
        log.debug("getting Customer instance with custName: " + custName);
        try {
            Customer instance = (Customer) getHibernateTemplate()
                    .get("org.xqm.db.Customer", custName);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
   
   
    public List findByExample(Customer instance) {
        log.debug("finding Customer instance by example");
        try {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }   
   
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding Customer instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Customer as model where model."
                                                         + propertyName + "= ?";
                 return getHibernateTemplate().find(queryString, value);
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
        }

        public List findByCustName(Object custName) {
                return findByProperty(CUST_NAME, custName);
        }
       
        public List findByPassword(Object password) {
                return findByProperty(PASSWORD, password);
        }
       
        public List findByEmail(Object email) {
                return findByProperty(EMAIL, email);
        }
       
    public Customer merge(Customer detachedInstance) {
        log.debug("merging Customer instance");
        try {
            Customer result = (Customer) getHibernateTemplate()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Customer instance) {
        log.debug("attaching dirty Customer instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
   
    public void attachClean(Customer instance) {
        log.debug("attaching clean Customer instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

        public static CustomerDAO getFromApplicationContext(ApplicationContext ctx) {
            return (CustomerDAO) ctx.getBean("CustomerDAO");
        }
}

大家帮忙看看呀....

论坛徽章:
0
6 [报告]
发表于 2007-04-02 13:48 |只看该作者

  1.         <id name="customerId" type="java.lang.Integer">
  2.             <column name="customer_id" />
  3.             <generator class="native" />
  4.         </id>
复制代码



决定了主键只能是 Integer 类型,你却用custName去 get

  1. Customer instance = (Customer) getHibernateTemplate()
  2.                     .get("org.xqm.db.Customer", custName);
复制代码


要根据不是主键条件的,去查找记录,就不能再用 load 或 get 了,写 SQL 或 HQL 查询吧

论坛徽章:
0
7 [报告]
发表于 2007-04-02 15:42 |只看该作者
哦..我知道了...谢谢.......................................

论坛徽章:
0
8 [报告]
发表于 2007-04-04 22:32 |只看该作者
自己解决了

要总结下方法 好让 后人不会有同样的错误
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP