Automatic Hibernate Transaction Management with Spring?

前端 未结 2 653
长发绾君心
长发绾君心 2020-12-13 21:55

How far does the spring framework go with transaction handling? My reading of the book \"Spring In Action\" suggestions with its examples that you create DAO methods that do

2条回答
  •  鱼传尺愫
    2020-12-13 22:50

    There is some work you are supposed to do to be able to do just that but it's not much at all. Supposedly, you will use JPA with pick your own provider, e.g. Hibernate. Then you need to place persistence.xml that defines the persistence unit in the META-INF folder:

    
    
                   
    
    

    Next, define everything necessary for database connection in the Spring application context you use, at minimum it should contain these:

    
            
                
                    /WEB-INF/jdbc.properties     
            
        
    
        
            
            
            
            
        
    
        
            
            
            
                
                    
                    
                    
                    
                
                 
        
    
        
            
            
        
    
    
    
    
    
     
    

    Some properties above may be changed or added depending on your needs. The example is for JPA with Hibernate and PostgreSQL database as you may have guessed.

    Now you can simply define your data access methods like this:

    @Repository
    @Transactional
    public class UserJpaDAO {
    
        protected EntityManager entityManager;
    
        @PersistenceContext
        public void setEntityManager(EntityManager entityManager) {
            this.entityManager = entityManager;
        }
    
        public void save(User theUser) {
            entityManager.persist(theUser);
        }
    
        public User update(User theUser) {
            return entityManager.merge(theUser);
        }
     }
    

    where User is a JPA entity defined by your application. You may manager transactions at manager/controller layer that calls your DAOs - in fact I do it that way - but I placed it together here not to clutter example too much.

    Nice references that you may want to go straight to instead of my examples is http://icoloma.blogspot.com/2006/11/jpa-and-spring-fucking-cooltm_26.html The top 3 links it references are worth going to as well.

提交回复
热议问题