Hibernate遇上Spring注释方法擦出的火花

在这篇博客中我直接使用sessionFactory来获得currentSession来操纵数据库,在我上一篇博客中出现的问题,HibernateTemplate在Hibernate4.0中被抛弃了,所以这个方法刚好解决了这个问题。
一、项目的结构图
Hibernate遇上Spring注释方法擦出的火花_第1张图片
二、具体实现
1、User类


@Entity
@Table(name="t_user")
public class User {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Integer id;
  @Column(name="username",length=50)
  private String username;
  @Column(name="password",length=50)
  private String password;
public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}

}

2、UserDao接口


public interface UserDao {
  public void save(User user);
  public void update(User user);
  public void delete(User user);
  public User findById(Integer id);
  public List findAll();
}

3、UserDaoImpl 类
采用事务功能提高代码的安全性,通过spring注释的方式自动加载sessionFactory通过setter方法


@Repository
public class UserDaoImpl  implements UserDao{
    private SessionFactory sessionFactory;
     @Autowired
    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory=sessionFactory;
    }
    public SessionFactory getSessionFactory(){
        return this.sessionFactory;
    }

    public Session getCurrentSession(){
        return this.sessionFactory.getCurrentSession();
    }
    public void save(User user) {
        Transaction tx=this.getCurrentSession().beginTransaction();
         try{
             this.getCurrentSession().save(user);
             tx.commit();
         }catch(Exception e){
             if(null!=tx){tx.rollback();}
             e.printStackTrace();
         }  
    }

    public void update(User user) {
        Transaction tx=this.getCurrentSession().beginTransaction();
         try{
             this.getCurrentSession().update(user);
             tx.commit();
         }catch(Exception e){
             if(null!=tx){tx.rollback();}
             e.printStackTrace();
         }  

    }

    public void delete(User user) {
        Transaction tx=this.getCurrentSession().beginTransaction();
         try{
             this.getCurrentSession().delete(user);
             tx.commit();
         }catch(Exception e){
             if(null!=tx){tx.rollback();}
             e.printStackTrace();
         }  
    }

    public User findById(Integer id) {
         Transaction tx=this.getCurrentSession().beginTransaction();
         User user=(User)this.getCurrentSession().get(User.class, id);
         tx.commit();
         return user;
    }

    public List findAll() {
         Transaction tx=this.getCurrentSession().beginTransaction();
         List users=(List) this.getCurrentSession().get(User.class,null);
         tx.commit();
         return users;
    }

}

4、applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:tx="http://www.springframework.org/schema/tx"
          xmlns:context="http://www.springframework.org/schema/context"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
        
        <context:component-scan base-package="cn.wjw">context:component-scan>
        
        <context:property-placeholder location="classpath:c3p0-db.properties"/>
        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="${jdbc.driverClass}">property>
          <property name="jdbcUrl" value="${jdbc.jdbcUrl}">property>
          <property name="user" value="${jdbc.user}">property>
          <property name="password" value="${jdbc.password}">property>
        bean>
  
  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  
  <property name="dataSource" ref="dataSource"/>
  
  <property name="hibernateProperties">
  <props>
  
  <prop key="hibernate.dialect">
    org.hibernate.dialect.MySQL5Dialect
  prop>
  
  <prop key="hibernate.show_sql">trueprop>
  
  <prop key="hibernate.hbm2ddl.auto">updateprop>
  
  <prop key="javax.persistence.validation.mode">noneprop>
  <prop key="hibernate.current_session_context_class">threadprop>
  <prop key="">prop>
  props>
  property>
        <property name="packagesToScan">
            <list>
                <value>cn.wjw.domainvalue>
            list>
        property> 
 bean>
  
  
  <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
   <property name="sessionFactory" ref="sessionFactory"/>
  bean>
  
  <tx:annotation-driven transaction-manager="txManager"/>
beans>

5、c3p0-db.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc\:mysql\://localhost\:3306/database?useUnicode\=true&;characterEncoding\=utf-8
jdbc.user=你的数据库用户名
jdbc.password=你的数据库密码

6、Spring注释的优点
使得代码简洁,但却可读性降低,但是在平时的开发中熟练这种方法有助于提高开发效率。

你可能感兴趣的:(hibernate,注释,spring,数据库)