1. 程式人生 > >Spring4.X整合hibernate5.X之事物管理

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

我們之所以要用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 {

	@Autowired
	private SessionFactory sessionFactory;
	
	
	@Override
	public void BasepathSet(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String 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
@RequestMapping

public class Index {

	@Autowired
	IndexService indexService;

	
	
	/*
	 * 跳轉首頁
	 * basepath 設定
	 */
	@Transactional
	@RequestMapping(value = "/index")
	String index(HttpServletRequest request, Model model){
		indexService.BasepathSet(request);
		indexService.Test();
		return "index";
	}
}

測試成功!如有疑問歡迎交流

相關連結: