SpringMvc整合hibernate
阅读原文时间:2023年09月16日阅读:4

之前用的比较多的是Mybatis,最近应客户要求准备hibernate的技术,给我最深的感触就是,能用mybatis尽量用mybatis,和hibernate相比优秀了不是一点半点,hibernate明显是简单问题复杂化,下面说一下简单配置。

1、准备jar包

这里面包括很多jar包,最初我只是加上了hibernate-core的包,但是怎么整都不行,后来发现因为缺少Spring的包。spring其他包这里不再多说,只介绍整合hibernate需要的包。

org.hibernate.javax.persistence hibernate-jpa-2.1-api 1.0.0.Final

org.hibernate hibernate-core 5.2.5.Final

org.springframework spring-orm 4.3.5.RELEASE

 <dependency>  
     <groupId>org.springframework</groupId>  
     <artifactId>spring-context</artifactId>  
     <version>4.3.5.RELEASE</version>  
 </dependency>

 <dependency>  
     <groupId>org.springframework</groupId>  
     <artifactId>spring-core</artifactId>  
     <version>4.3.5.RELEASE</version>  
 </dependency>

 <dependency>  
     <groupId>org.springframework</groupId>  
     <artifactId>spring-beans</artifactId>  
     <version>4.3.5.RELEASE</version>  
 </dependency>

 <dependency>  
     <groupId>org.springframework</groupId>  
     <artifactId>spring-expression</artifactId>  
     <version>4.3.5.RELEASE</version>  
 </dependency>

 <dependency>  
     <groupId>org.springframework</groupId>  
     <artifactId>spring-aop</artifactId>  
     <version>4.3.5.RELEASE</version>  
 </dependency>

2、修改配置文件

首先创建一个新的Spring-hibernate配置文件


http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

 <context:component-scan base-package="com.XXX.dao"/>

 <context:property-placeholder location="classpath:jdbc.properties" />

  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">  
     <property name="dataSource" ref="dataSource" />  
     <property name="packagesToScan">  
         <list>  
             <value>com.XX.model</value>  
         </list>  
     </property>  
     <property name="hibernateProperties">  
         <props>  
             <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
             <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
             <prop key="hibernate.show\_sql">${hibernate.show\_sql}</prop>  
             <!--  <prop key="hibernate.current\_session\_context\_class">thread</prop> -->  
         </props>  
     </property>  
 </bean>

 <!-- 数据库映射 -->  
 <!--  class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" -->  
 <!--  class="org.springframework.jdbc.datasource.DriverManagerDataSource" -->  
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
   <property name="driverClassName" value="${jdbc.driverClassName}" />  
   <property name="url" value="${jdbc.url}" />  
   <property name="username" value="${jdbc.username}" />  
   <property name="password" value="${jdbc.password}" />  
</bean>

 <!-- 配置Hibernate事务管理器 -->  
 <bean id="transactionManager"  
     class="org.springframework.orm.hibernate5.HibernateTransactionManager">  
   <property name="sessionFactory" ref="sessionFactory" />  
</bean>

<!-- 配置事务异常封装 -->  
<bean id="persistenceExceptionTranslationPostProcessor"  
    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<!--  声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->  
 <tx:advice id="txAdvice" transaction-manager="transactionManager">  
     <tx:attributes>  
         <tx:method name="add\*" propagation="REQUIRED" />  
         <tx:method name="get\*" propagation="REQUIRED" />  
         <tx:method name="\*" read-only="true" />  
     </tx:attributes>  
 </tx:advice>  

jdbc.properties 配置文件中的内容不再多说,根据自己的实际环境配置,其中要注意的一个地方是hibernate.hbm2ddl.auto
这里一定要看清,如果配错,很容易把你数据表给重构了,详细参照下边

3、创建测试代码

首先是Entity,这里尽量和表结构保持一致

import javax.persistence.*;

@Entity
@Table(name="user")
public class Users {

 @Id  
 @GeneratedValue(strategy=GenerationType.AUTO)  
 @Column(name="userId")  
 private int userId;

 @Column(name="UserName",length=50)  
 private String userName;

 public int getUserId() {  
     return userId;  
 }

 public void setUserId(int userId) {  
     this.userId = userId;  
 }

 public String getUserName() {  
     return userName;  
 }

 public void setUserName(String userName) {  
     this.userName = userName;  
 }  

}

然后是Dao层

@Component
public class UsersDAO extends HibernateDaoSupport {
@Autowired
public void setMySessionFactory(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}

 @SuppressWarnings({ "rawtypes", "unchecked" })  
 public List<Users> getAllUser(){  
     String hsql="from Users";  
     Session session = super.getSessionFactory().openSession();  
     Query query = session.createQuery(hsql);

     return query.getResultList();  
 }  

}

这里注意一点,实际项目中最好做一个basedao,去继承HibernateDaoSupport,而且必须加上setMySessionFactory方法,这样做的目的是为了把SessionFactory注入到Dao中,除非在Xml中注入,但是个人感觉注解更好用。

最后就是创建个Service类去调用dao层,再用Controller层去调用Service层就Ok了。

关键就在于配置文件和Dao层注入,其他没什么难点,但是比起Mybatis来还是复杂很多,Mybatis还天然支持预处理语句,hibernate貌似还要用HibernateTemplate,这个没仔细研究,感觉特别麻烦。