Spring与Hibernate的整合,不配置事务管理器,事务会自动提交(Hibernate默认手动提交)

数据库为MySQL,Spring版本3.2.1,Hibernate版本3.3.2。

Spring配置文件:

  
  
       
      
      
          
          
          
        
        
        
        
        
      
      
      
      
          
          
             
                com/zzj/entity/Config.hbm.xml  
              
        
          
              
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                hibernate.show_sql=true
              
          
     
    
     
    
    	
    
      
  

实体类:

package com.zzj.entity;

public class Config {
	private Integer id;
	private String name;
	private String value;
	
	public Config() {
	}
	
	public Config(Integer id, String name, String value) {
		this.id = id;
		this.name = name;
		this.value = value;
	}

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "Config [id=" + id + ", name=" + name + ", value=" + value + "]";
	}
	
}
Hibernate映射文件:
    
  
  
    
        
            
        
        
        
    

Dao类:
package com.zzj.dao;

import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ConfigDao extends HibernateDaoSupport {
	
	public void save(){
		getHibernateTemplate().execute(new HibernateCallback() {

			@SuppressWarnings("deprecation")
			@Override
			public Integer doInHibernate(Session session) throws HibernateException, SQLException {
				System.out.println("autoCommit:" + session.connection().getAutoCommit());
				
				Query query = session.createQuery("update Config set value = :value where name = :name");
				query.setString("name", "Tom");
				query.setString("value", "11");
				return query.executeUpdate();
			}
		});
	}
}
测试类:
package com.zzj;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.zzj.dao.ConfigDao;

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-common.xml");
		ConfigDao configDao = (ConfigDao) context.getBean("configDao");
		configDao.save();
	}
}

Spring没有配置事务管理器,Dao类中也没有开启和提交事务的操作,事务也提交了!

注意:Dao类中输出的autoCommit为true。





你可能感兴趣的:(Spring)