日期:2014-05-20  浏览次数:20666 次

Hibernate的级联的事务问题
主表:School(id,s_name),子表Teacher(t_id,t_s_id,t_name)其中t_s_id为外键与School的id关联,关系cascade
config.xml:
<!--Transaction-->
<tx:annotation-driven transaction-manager="txManager"/>

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="proxyTemplate" name="proxyTemplate"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,+Exception</prop>
<prop key="insert*">PROPAGATION_REQUIRED,+Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,+Exception</prop>
<prop key="remove*">PROPAGATION_REQUIRED,+Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,+Exception</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="service" parent="proxyTemplate">
<property name="target">
<ref local="hstudao" />
</property>
</bean>
<!--schooldao-->
<bean id="schooldao" class="com.ydx.stu.SchoolDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

stu.hbm.xml:
<hibernate-mapping package="com.ydx.stu" auto-import="true">
<class name="School" table="school" lazy="false">
<id name="id" type="int" column="id" length="4"></id>
<property name="s_name" type="string" column="s_name" length="45"></property>
<set name="teacher_set" inverse="true">
<key column="t_id"></key>
<one-to-many class="Teacher" />
</set>
<set name="student_set" inverse="true">
<key column="stu_s_id"></key>
<one-to-many class="Student" />
</set>
</class>
<class name="Teacher" table="teacher" lazy="false">
<id name="t_id" type="string" column="t_id" length="45"></id>
<property name="t_name" type="string" column="t_name" length="45"></property>
<many-to-one class="School" column="t_s_id" name="school" cascade="save-update"></many-to-one>
</class>
</hibernate-mapping>

[code:]

dao.java: extends HibernateDaoSupport
  public void insertTeacher(Teacher teacher) {
  getHibernateTemplate().save(teacher);
  }

test.java:
school = new School();
school.setId(11);
school.setS_name("ShenZhen11");

teacher1 = new Teacher();
teacher1.setSchool(school);
teacher1.setT_id("T1009");
teacher1.setT_name("Mr.hee");