hibernate的常见错误解决方法

2014-02-06 12:40

1、

org.springframework.orm.ObjectRetrievalFailureException: Object of class [com.xindeco.myregister.pojo.MyRegisterInfo] with identifier [14]: not found

MyRegisterInfo在数据库没有identifier [14]对象。

2、

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.xindeco.myregister.pojo.MyRegisterInfo column: password (should be mapped with insert="false" update="false")

出错原因:password 和repassword同时对应数据库表中的password一列,同时update和insert都设为true。

xml文件如下:

    <property name="password"

                          type="java.lang.String"

                          update="true"

                          insert="true"

                          access="property"

                          column="password"

                          length = "32"

                          />

                         <property name="repassword"

                          type="java.lang.String"

                          update="false"

                          insert="false"

                          access="property"

                          column="password"

                          length = "32"

                          />

解决的方法:

将repassword的insert和update设为false。

3、

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed;

nested exception is org.hibernate.PropertyNotFoundException: Could not find a getter for ID in class

错误原因:hibernate的映射文件中ID是大写的,而pojo的类中id是小写的

注意事项:每个pojo的类都要继承abstractEntity,其中abstractEntity类有个ID的属性要重写

public abstract class AbstractEntity

    implements Entity, BaseDTO {

    abstract public long getID();

    abstract public void setID(long id);

    public int hashCode() {

        return (int)this.getID();

    }

    public boolean equals(Object obj) {

        if (obj == this) {

            return true;

        }

        if (obj instanceof Entity) {

            return this.getID() == ( (Entity) obj).getID();

        }

        return false;

    }

}

4、

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition

错误原因:

在application.xml文件中deleteRegister方法以delete开头,并没有被设定为可更改的,应如下设置:

<!--为事物创建代理类,并指定方法的事物类型-->

<bean id="baseTxProxy" lazy-init="true" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">

    <property name="transactionManager">

      <ref bean="transactionManager"/>

    </property>

    <property name="transactionAttributes">

      <props>

        <prop key="add*">PROPAGATION_REQUIRED</prop>

        <prop key="cancel*">PROPAGATION_REQUIRED</prop>

           </props>

    </property>

</bean>

加上一行

<prop key="delete*">PROPAGATION_REQUIRED</prop>

5、

   ERROR org.apache.struts.util.RequestUtils - Error creating form bean of class com.xindeco.business.web.form.GraAppInfoForm

public class GraAppInfoForm

extends ActionForm 错误写成

public abstratic class GraAppInfoForm

extends ActionForm

6、

2006-04-25 08:56:38,495 ERROR com.xindeco.business.web.action.GraAppAction - com.xindeco.business.web.action.GraAppAction@8e2fb5

java.lang.ClassCastException: $Proxy0

at com.xindeco.business.web.action.GraAppAction.newone(GraAppAction.java:30)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:585)

at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:274)

at com.xindeco.core.web.action.BaseAction.dispatchMethod(BaseAction.java:153)

at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:194)

actioin类中的newone方法如下:

public class GraAppAction

    extends BaseAction {

    public ActionForward newone(ActionMapping mapping, ActionForm form,

                              HttpServletRequest request,

                              HttpServletResponse response) throws Exception {

       GraAppService graservice = (GraAppService) this.getBean("GraAppService");

}

applicationcontext中的GraAppService的配置如下:

    <bean id="GraAppDAO" class="com.xindeco.business.dao.impl.GraAppDAOImpl">

    <property name="support">

      <ref local="support"/>

    </property>

    <property name="sessionFactory">

      <ref local="sessionFactory"/>

    </property>

</bean>

<bean id="GraAppService" parent="baseTxProxy">

    <property name="target">

      <bean class="com.xindeco.business.service.impl.GraAppServiceImpl" autowire="byName">

        <property name="baseDAO">

          <ref bean="GraAppDAO"/>

        </property>

      </bean>

    </property>

</bean>

因此this.getBean("GraAppService");是为了得到GraAppServicImpl类的实现。GraAppService是interface

public class GraAppServiceImpl extends BaseServiceImpl

    implements GraAppService{

}

7、org.hibernate.hql.ast.QuerySyntaxException: Demand is not mapped. [from Demand where unitid = ? and needNum > usedNeedNum]

hibernate.cfg.xml没有配置Demand.hbm.xml文件的目录

8、org.springframework.jdbc.BadSqlGrammarException: Bad SQL grammar [] in task 'Hibernate operation'; nested exception is java.sql.SQLException: 列名 'id' 无效。

java.sql.SQLException: 列名 'name' 无效。

因为hibernate声明的id,name的columnid属性没有与数据库的字段对应,所以id,name无效。

9、java.lang.NumberFormatException: null

at java.lang.Integer.parseInt(Integer.java:415)

at java.lang.Integer.parseInt(Integer.java:497)

at com.xindeco.business.service.impl.DemandServiceImpl.findDemandListByUnitId(DemandServiceImpl.java:33)

错误语句为

needNum = Integer.parseInt(demand.getNeedNum());

usedNeedNum = Integer.parseInt(demand.getUsedNeedNum());

因为demand.getUsedNeedNum()==null,无法转化为string 类型,

10、rg.apache.jasper.JasperException: /GraAppInfo/GraAppInfoNew.jsp(343,29) According to TLD, tag bean:write must be empty, but is not

错误的原因:

       <select name="politicsID" >

             <option value="">请选择</option>

       <logic:notEmpty name="politicsList">

                <logic:iterate id="politics" name="politicsList">

       </logic:notEmpty>

       <option value="<bean:write name="politics" property="codeID"/>"><bean:write name="politics" property="codeName"/></option>

       </logic:iterate>

</select>

就因为少了/>

以后懂得通过查找字数,来检查错误

11、2006-04-26 13:27:54,812 ERROR com.xindeco.core.util.BeanUtils - bean property [Nation] copy failed

com.xindeco.core.exception.ConvertException: org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: java.lang.String; nested exception is org.hibernate.MappingException: Unknown entity: java.lang.String

beanUtil.beanCopy(grapojo,form,BizConstants.CONVERTER);

要求:

1、pojo类的属性只有与form属性名字相同,才能beancopy成功

2、pojo中属性是实体,在form中一定要用int,long表示

出现这错误的原因是pojo中的属性不是实体,而错误写成:

string

private String nation;应改成 private Syscode nation;

12、

2006-04-26 14:38:37,843 ERROR com.xindeco.business.web.action.GraAppAction - com.xindeco.business.web.action.GraAppAction@fa1b2d

java.lang.NullPointerException

at com.xindeco.business.web.action.GraAppAction.newone(GraAppAction.java:43)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

hibernate配置文件没改,程序找不到相应的类

        <many-to-one

            name="FSUnit"

            class="com.xindeco.business.pojo.EmployUnitBaseInfo"

            cascade="none"

            outer-join="auto"

            update="true"

            insert="true"

            access="property"

            column="fSUnit"

        />

其实FSUnit对应的类应该是FSUnit

        <many-to-one

            name="FSUnit"

            class="com.xindeco.business.pojo.FSUnit"

            cascade="none"

            outer-join="auto"

            update="true"

            insert="true"

            access="property"

            column="fSUnit"

        />

13、

org.hibernate.MappingException: An association from the table GraAppInfo refers to an unmapped class: com.xindeco.business.pojo.FSUnit

错误原因:hibernate.cfg.xml没有配置fsunit.hbm.xml文件的位置

14、

java.lang.ClassCastException: com.xindeco.business.dao.impl.GraAppDAOImpl

at com.xindeco.business.service.impl.GraAppServiceImpl.addGraduateApp(GraAppServiceImpl.java:16)

GraAppServiceImpl.java:16

第16行: GraAppDAO dao = (GraAppDAO) this.getBaseDAO();//其实得到的是GraAppDAOImpl

错误的原因是

public class GraAppDAOImpl

    extends BaseDAOImpl {

}

没有实现GraAppDAO接口,正确的做法是

public class GraAppDAOImpl

    extends BaseDAOImpl implements GraAppDAO {

}

先继承后实现

15、2006-04-27 08:38:54,078 ERROR com.xindeco.business.web.action.GraAppAction - com.xindeco.business.web.action.GraAppAction@1d6399b

java.lang.ClassCastException: com.xindeco.business.pojo.SysCode

at org.hibernate.type.StringType.set(StringType.java:26)

at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:63)

at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:40)

一般是因为hibernate声明类型和pojo类声明的类型不一样,并且前面已经出现了Hibernate: insert into TGraAppInfo (name, whereFrom, degree, college, speciality, studentRelTel, remark, higherEduLength, highSchool, studyResume, normalOrNot, proxyUnit, workPost, workPlace, studentAddress, studentPostNumber, nation, appStatus) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

的操作提示,查出错误的原因有:

        <many-to-one

            name="demand"

            class="com.xindeco.business.pojo.Syscode"

            cascade="none"

            outer-join="auto"

            update="true"

            insert="true"

            access="property"

            column="demandID"

        />

         <property

            name="appStatus"

            type="int"

            update="true"

            insert="true"

            access="property"

            column="appStatus"

            length="10"

        />

应改为   

        <many-to-one

            name="demand"

            class="com.xindeco.business.pojo.Demand"

            cascade="none"

            outer-join="auto"

            update="true"

            insert="true"

            access="property"

            column="demandID"

        />

<many-to-one

            name="nation"

            class="com.xindeco.business.pojo.SysCode"

            cascade="none"

            outer-join="auto"

            update="true"

            insert="true"

            access="property"

            column="nation"

        />

16、

org.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing: com.xindeco.business.pojo.SysCode

at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:626)

at org.springframework.orm.hibernate3.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:570)

at

org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:482)

pojo类为:

public class GraAppInfo{

    private College college;

}

action 类为

public class GraAppAction

    extends BaseAction {

       public ActionForward add(ActionMapping mapping, ActionForm form,

                             HttpServletRequest request,

                             HttpServletResponse response) throws Exception {

        graInfo.setCollege(new College());\\必须从数据库找到college这个对象,而不能新生成

        graInfo.getCollege().setID(graForm.getCollegeID());

        graInfo.setAppStatus(Integer.parseInt("0"));

      service.addGraduateApp(graInfo);

}

public class GraAppServiceImpl extends BaseServiceImpl

    implements GraAppService{

    public boolean addGraduateApp(GraAppInfo info){

        this.getBaseDAO().save(info);

        return true;

    }

}

dao类save方法为

    getHibernateTemplate().save(obj);

当cascade="all",插入new college 除了id和原来的记录一样,其他的字段全部都被更新,为null

当cascase=“insert”,插入new college 只会把它的id插入grainfo表中,其他字段不变。

17、java.sql.SQLException: Unable to convert between java.lang.Integer and BLOB.

因为

        <property

            name="province"

            type="com.xindeco.business.pojo.SysCode"//不能用复杂类,

            update="true"

            insert="true"

            access="property"

            column="provinceId"

        />

应该改为

            <many-to-one

            name="province"

            class="com.xindeco.business.pojo.SysCode"

            cascade="none"

            outer-join="auto"

            update="true"

            insert="true"

            access="property"

            column="provinceId"

        />

18、javax.servlet.jsp.JspException: Cannot create iterator for this collection

at org.apache.struts.taglib.logic.IterateTag.doStartTag(IterateTag.java:265)

jsp文件如下:

   <logic:notEmpty name="graduateList" >

   <logic:iterate id="graduate" name="graduateList" >

   </ogic:notEmpty >

   </ogic:iterat>

graduateList是一个类,而logic:iterator要求必须是ArrayList,HashSet....这样的集合类,而graduateList中一个属性是ArrayList或HashSet的

应改为:

<logic:notEmpty name="graduateList" property="items">

<logic:iterate id="graduate" name="graduateList" property="items" >

</ogic:notEmpty >

</ogic:iterat>

19、2006-05-11 17:13:37,468 ERROR com.xindeco.business.web.action.GraAppAction - com.xindeco.business.web.action.GraAppAction@bc22eb

org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed

SysUser user= (SysUser) request.getSession().getAttribute(WebConstants.SESSION_USER);

System.out.println(user.getRole().getRoleName());

当hibernate session取出数据放到http session时,

由于sysuser中role的lazy=“true”,所以没有将RoleName放到http session中,当System.out.println(user.getRole().getRoleName());

时,虽然http session还开着, hibernat seesion已经关闭

        <many-to-one

            name="role"

            class="com.xindeco.business.pojo.SysRole"

            lazy="false"

            cascade="none"

            outer-join="auto"

            update="true"

            insert="true"

            access="property"

            column="roleID"

        />

20、Association references unmapped class: com.xindeco.workflow.WFNode

因为application.xml文件中没有配置<mapping resource="com/xindeco/workflow/WFNode.hbm.xml"/>

系统找不到WFNode

         < set

     name = " nodes "

            table = " WF_ROLENODES "

            lazy = " true "

            inverse = " false "

            cascade = " none "

            sort = " unsorted "

         >

< key column = " roleID " > </ key >               

< many - to - many

         class = " com.xindeco.workflow.WFNode "

         column = " nodeId "

         outer - join = " auto " />

         </ set >