Spring4.X整合hibernate5.X之事物管理

来源:互联网 发布:win10 ubuntu双系统 编辑:程序博客网 时间:2024/06/06 16:32

我们之所以要用Transaction来管理hibernate的session主要目的就是区分开业务逻辑代码和持久层代码分开。

我所做是在正确导入了相关jar包和配置好了spring mvc的前提条件下进行的,下面是我的一个在eclipse下面的测试项目的项目目录结构


第一步:配置springmvc-servlet.xml文件标红的是关于事物管理方面的类容,但是其他配置也不可少

<?xml version="1.0" encoding="UTF-8"?><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:p="http://www.springframework.org/schema/p"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd"        >    <aop:aspectj-autoproxy/>       <!-- aop支持 -->    <mvc:annotation-driven/>       <!-- mvc支持 -->    <tx:annotation-driven/>        <!-- 事务管理支持 -->    <context:component-scan base-package="znck.spring.*"/><!-- 注解支持,添加要扫描的包 -->        <bean id="viewResolver"        class="org.springframework.web.servlet.view.UrlBasedViewResolver">    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>    <property name="prefix" value="/WEB-INF/jsp/"/>    <property name="suffix" value=".jsp"/>    </bean>   <!-- 视图解析器 -->        <import resource="classpath:/hibernate_spring.cfg.xml"/><!-- 导入hibernate配置 -->    <bean id="transactionManager"            class="org.springframework.orm.hibernate5.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"/>    <!-- 引入sessionFactory -->    </bean><!-- 事务管理器 -->        <bean id="multipartResolver"        class="org.springframework.web.multipart.support.StandardServletMultipartResolver">    </bean><!-- 文件上传servlet3.0 -->    </beans>

看到其中标注红色的部分就是关于事物的配置,还有一个AOP的配置,是因为事物需要AOP的支持,另外绿色的部分则是导入了相关hibernate的配置,包括数据源SessionFactory等,下面是hibernate_spring.cfg.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">    <property name="driverClass" value="com.mysql.jdbc.Driver"/>    <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/znck"/>    <property name="user" value="root"/>    <property name="password" value="1234"/></bean>      <!-- 这里数据源配置我采用了默认配置 -->    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource"/>        <property name="packagesToScan">      <!-- 指定映射类扫描实体化类/映射类 -->       <list>            <value>znck.hb.entity.*</value>        </list>      </property>        <property name="hibernateProperties">           <props>           <prop key="hibernate.hbm2ddl.auto">update</prop>    <!-- 指定hibernate是否要根据持久化类自动建立数据表 -->           <prop key="hibernate.show_sql">true</prop>         <!-- 显示Hibernate持久化操作所生成的SQL -->           <prop key="hibernate.format_sql">true</prop>   <!-- 将SQL脚本进行格式化后再输出 -->           <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>   <!-- 指定数据库方言 -->           <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop><!-- 排除掉数据库可能不支持的功能 -->           </props>        </property>    </bean>    </beans>

下面是我的User实体化类

package znck.hb.entity.user;import java.io.Serializable;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="user")public class User implements Serializable {/** * 序列化 */private static final long serialVersionUID = 1L;/* * 用户账号/标识属性 */@Id@GeneratedValue(strategy=GenerationType.IDENTITY)private int account;/* * 密码 */private String password;/* * 手机 */private String phone;/* * 邮箱 */private String email;/* * 用户昵称 */private String name;public int getAccount() {return account;}public void setAccount(int account) {this.account = account;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

IndexService接口,test()为测试方法

package znck.spring.service.index;import javax.servlet.http.HttpServletRequest;public interface IndexService {/* * 基础路径设置 * 在serveletContext中保存basepath */void BasepathSet(HttpServletRequest request);void Test();}

IndexServiceImp类

package znck.spring.serviceImp.index;import javax.servlet.http.HttpServletRequest;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import znck.hb.entity.user.User;import znck.spring.service.index.IndexService;@Service@Transactional           //事物注释必须要在service中否则无效public class IndexServiceImp implements IndexService {@Autowiredprivate SessionFactory sessionFactory;@Overridepublic void BasepathSet(HttpServletRequest request) {// TODO Auto-generated method stubString basepath = ((HttpServletRequest)request).getRequestURL().toString();basepath = basepath.substring(0, basepath.length()-1);if(request.getServletContext().getAttribute("basepath")==null){request.getServletContext().setAttribute("basepath", basepath);            //设置基础路径}}/* * test */public void Test(){User user = new User();user.setAccount(1231);sessionFactory.getCurrentSession().save(user);}}

Index类

package znck.spring.control.index;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.transaction.annotation.Transactional;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import znck.spring.service.index.IndexService;@Controller@RequestMappingpublic class Index {@AutowiredIndexService indexService;/* * 跳转首页 * basepath 设置 */@Transactional@RequestMapping(value = "/index")String index(HttpServletRequest request, Model model){indexService.BasepathSet(request);indexService.Test();return "index";}}

测试成功!如有疑问欢迎交流

相关链接:

C3P0的三种配置方式以及基本配置项详解

Hibernate配置各种数据源详解

c3p0详细配置






原创粉丝点击