日期:2014-05-18 浏览次数:20723 次
@Test
public void deleteDept(){
Session session = null;
try {
session = HibernateUtil.getSession();
session.setFlushMode(FlushMode.AUTO);
session.beginTransaction().begin();
Dept dept = new Dept();
dept.setId(1);
session.delete(dept);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtil.close(session);
}
}
<set cascade="all" lazy="extra" name="emps" inverse="false">
<key column="did"/>
<one-to-many class="entity.Emp"/>
</set>
Dept dept = (Dept) session.load(Dept.class, 5);
session.delete(dept);
<set cascade="all" lazy="extra" name="emps" inverse="false">
<key column="did" on-delete="cascade"/>
<one-to-many class="entity.Emp"/>
</set>
org.hibernate.MappingException: only inverse one-to-many associations may use on-delete="cascade": entity.Dept.emps
at org.hibernate.mapping.Collection.validate(Collection.java:267)
at org.hibernate.mapping.Set.validate(Set.java:19)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1112)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1293)
at util.HibernateUtil.<clinit>(HibernateUtil.java:14)
at test.testEmp.deleteDept(testEmp.java:102)
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:597)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:88)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.