用Spring整合Hibernate。没有用事务,Spring配置如下:
[code="java"]
class="org.apache.commons.dbcp.BasicDataSource">
value="com.mysql.jdbc.Driver">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
[color=red]<prop key="hibernate.connection.autocommit">false</prop>[/color]
</props>
</property>
<property name="mappingResources">
<list>
<value>vo/Student.hbm.xml</value>
</list>
</property>
</bean>
[/code]
public class StudentDaoImpl extends HibernateDaoSupport implements StudentDao{
public void save(Student stu) {
[color=red]this.getHibernateTemplate().save(stu); //问题:为什么上面设置autocommit为false,但这里还是会提交到数据库中[/color]
}
}
[b]问题补充:[/b]
谢谢你的回复。
我用的是MySQL,但我发现即使加个声明式事务,调用getHibernateTemplate().save(stu)方法还是会插入到数据库中。以下是我的事务配置:
<bean id="studentDaoProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
<property name="target">
<ref local="studentDao"/>
</property>
</bean>
<bean id="studentDao" class="vo.StudentDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
这是我的测试类:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao studentDao = (StudentDao)context.getBean("studentDaoProxy");
//添加操作
Student student = new Student();
student.setName("测试");
studentDao.save(student);
}
}
hibernate事务是依赖与数据库事务的,调用save方法后SQL语句已经发送到数据库,所以提交到数据库很正常,如果你应用了事务但是autocommit为false才不会保存到数据库,前提是你的表是InnoDB(支持事务),如果是MyISAM(不支持事务)的话不管你是否应用了事务只要调用save方法数据库中都会存入记录
回答2:如果你save了对象,那么hibernate并没有把数据存入数据库,这时这个对象存在内存中,这时你如果使用get或者load方法取这个对象,你可以取到,也许你会误认为,这个对象存在数据库中,其实它还在内存中,hibernate回在合适的时候(一般是内存中的临时对象和持久化对象达到一定容量)把内存中的持久化对象同步到数据库中。如果你想强行把内存中的数据同步到数据库中,可以使用那个session的flush方法。