Spring Hibernate transaction management

前端 未结 1 1101
感情败类
感情败类 2020-12-14 13:21

I have just started making a project using spring and hibernate. My DAO layer class extends HibernateDaoSupport. We are not using annotations. Earlier, we were using struts

1条回答
  •  借酒劲吻你
    2020-12-14 14:15

    A few things are not clear from your question. My explanation follows based on below assumptions -

    • You are using spring to create a datasource and session factory
    • You are using Java 5 or above and could use annotations.

    Here is what your spring configuration would look like.

        
        
        
        
        
    
    
    
        
        
            
                product.hbm.xml
            
        
        
            
                hibernate.dialect=org.hibernate.dialect.HSQLDialect
            
        
    
    
    
        
     
    
    
    

    Once this is set up, you could use spring transactional annotations on your DAO methods as shown below. Spring would take care of starting transactions, committing your transactions or rolling back your transactions when exceptions are thrown. If you have business services, you would ideally use transactional annotations on your services instead of DAOs.

    @Transactional(propagation=Propagation.REQUIRED)
    public class MyTestDao extends HibernateDaoSupport {    
    public void saveEntity(Entity entity){
        getHibernateTemplate().save(entity);
    }
    @Transactional(readOnly=true)
    public Entity getEntity(Integer id){
        return getHibernateTemplate().get(Entity.class, id);
    }
     }
    

    Below code shows how transaction management could be achieve using spring's support for AOP rather than annotations.

        
    
    
    
       
    
    
    
    
    
    
        
            
            
            
            
        
    
    
    
    
        
        
    
    

    For additional details, please see - Spring Declarative Transactions

    0 讨论(0)
提交回复
热议问题