整合spring和hibernate需要五个要素,分别包括持久化的类, 数据源,SessionFactory, TransactionManager和持久化操作的DAO类。

持久化类:

@Entity  public class Spitter {      private long id;      private String userName, passWord, fullName;            public Spitter(long id, String n, String p, String f){          this.id = id;          this.userName = n;          this.passWord = p;          this.fullName = f;      }      public Spitter(){}      public void setId(long id){          this.id = id;      }      @Id      public long getId(){          return id;      }      public String getUserName(){          return this.userName;      }      public void setUserName(String n){          this.userName = n;      }      public String getPassWord(){          return this.passWord;      }      public void setPassWord(String p){          this.passWord = p;      }      public String getFullName(){          return this.fullName;      }      public void setFullName(String f){          this.fullName = f;      }    }

数据源(在spring配置文件中配置):

      
      
      
      
      
      
  

SessionFactory类(在spring配置文件中配置):

      
      
          
              
Spitter.spitterOne.Spitter
          
              
          
              
org.hibernate.dialect.MySQLInnoDBDialect              
true              
true              
update                        
              

配置hibernate事务:

        
           
                  
       

进行持久化操作的DAO类:

@Repository  public class HibernateSpitterDao implements SpitterDAO {      private SessionFactory sessionFactory;            @Autowired      public HibernateSpitterDao(SessionFactory sessionFactory){          this.sessionFactory = sessionFactory;      }      private Session currentSession(){          return this.sessionFactory.getCurrentSession();      }      /**      * 进行持久化的方法需要使用@Transactional进行事务管理      */      @Transactional(readOnly = false, rollbackFor = RuntimeException.class)      public void addSpitter(Spitter spitter){          this.currentSession().save(spitter);      }      public Spitter getSpitterById(long id){          return (Spitter)this.currentSession().get(Spitter.class, id);      }      @Transactional(readOnly = false, rollbackFor = RuntimeException.class)      public void saveSpitter(Spitter spitter){          this.currentSession().update(spitter);      }      public static void main(String [] args){          Spitter ss = new Spitter(103,"zhang sfdasf454352an", "cccninini", "zhang shan fdasfsdfewe");                ApplicationContext ctx = new ClassPathXmlApplicationContext("Spitter/spitterOne/spring-idol.xml");                  
SpitterDAO dao = (SpitterDAO) ctx.getBean("hibernateSpitterDao");          dao.addSpitter(ss);                }  }