天天看点

Spring集成Hibernate注意事项

项目原先有SpringMVC框架,后台希望加上hibernate框架的可以起看下,或者希望Spring集成hibernate。这里我用的是Spring4.2.1和hibernate4.3

web.xm上需要添加

  <filter>

  <filter-name>SpringOpenSessionInViewFilter</filter-name>

  <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>

  </filter>

  <filter-mapping>

          <filter-name>SpringOpenSessionInViewFilter</filter-name>

          <url-pattern>/*</url-pattern>

  </filter-mapping>

在原先applicationContext.xml文件中添加

<!-- hibernate配置文件 -->

<bean id="sessionFactory"

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<property name="dataSource">

<ref bean="dataSource" />

</property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">

org.hibernate.dialect.MySQLMyISAMDialect

</prop>

<prop key="hibernate.show_sql">true</prop>

</props>

</property>

<property name="mappingResources">

<list>

<value>

<!--这里是你的model对应的xml文件-->

sun/hao/model/identity/BydIdentityRole.hbm.xml

</value>

</list>

</property>

</bean>

<!-- 事务管理 -->

<bean id="txManager"   

        class="org.springframework.orm.hibernate4.HibernateTransactionManager">   

        <property name="sessionFactory" ref="sessionFactory" />

    </bean> 

    <!-- 用注解来控制事务管理 -->     

    <tx:annotation-driven transaction-manager="txManager" /> 

如果在项目中要用到事务的时候直接@Transactional