hibernate级联删除

今天写个级联删除始终报错:Could not execute JDBC batch update,后来发现是calsses.hbm.xml:中的inverse="false"(主控方)的原因,将它改为inverse="true"(被控方)后就ok了,inverse为false,classes就要维护student,在执行删除时会update关联的student设置其classid,但classid为null,如果studnet表中的classid为非空则会出以上异常。

下面是代码:

 

calsses.hbm.xml:

<class name="com.demoOne.bean.Classes" table="tclass" catalog="testdb">
        <id name="id" type="java.lang.Integer">
            <column name="id" length="4" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="80" />
        </property>
        <property name="banzhuren" type="java.lang.String">
            <column name="banzhuren" />
        </property>
        <set name="students" cascade="all-delete-orphan" inverse="true">
            <key>
                <column name="classid" length="4" />
            </key>
            <one-to-many class="com.demoOne.bean.Studnet" />
        </set>
    </class>

 

studeng.hbm.xml:

<class name="com.demoOne.bean.Studnet" table="tstudents" catalog="testdb">
  <id name="id" type="java.lang.Integer">
   <column name="id" length="4"/>
   <generator class="identity"></generator>
  </id>
  <property name="age" type="java.lang.Integer">
   <column name="age" length="3" />
  </property>
  <property name="name" type="java.lang.String">
   <column name="name" length="50" />
  </property>
  <property name="sex" type="java.lang.String">
   <column name="sex" length="3" />
  </property>
  <property name="birthday" type="java.sql.Date">
   <column name="birthday" length="11" />
  </property>
  <many-to-one name="classes" class="com.demoOne.bean.Classes" fetch="select">
   <column name="classid" />
  </many-to-one>
 </class>

 

delete方法:

@Override
 public void delete(Classes classes) {
  sessionFactory = getSessionFactory();
  Session session = sessionFactory.openSession();
  session.setFlushMode(FlushMode.AUTO);
  session.beginTransaction().begin();
  session.delete(classes);
  session.beginTransaction().commit();
  session.close();
  sessionFactory.close();
 }

 

 

你可能感兴趣的:(java,sql,bean,Hibernate,xml)