Spring MVC 트랜잭션 구성 상세 정보

16778 단어 SpringMVC사무
트랜잭션 구성의 모든 방법을 보려면 를 참조하십시오.
이 문서에서는 다음과 같은 두 가지 구성 방법을 설명합니다.
1. XML, tx 태그 설정 차단기로 사무 수행
2. Annotation 방식
다음 사용 환경은 Spring4.0.3, Hibernate4.3.5
1. XML, tx 태그 설정 차단기로 사무 수행
Entity 클래스 User.java, 지속화 클래스, 데이터베이스 테이블user 대응

package com.lei.demo.entity;

import javax.persistence.*;

@Entity(name="users")
public class Users {
  
  public Users(){
    super();
  }
  
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  @Column(name="id")
  private Integer id;
  
  @Column(name="user_name",length=32)
  private String user_name;
  
  @Column(name="age")
  private Integer age;
  
  @Column(name="nice_name",length=32)
  private String nice_name;
  
  // ......

}

UserDAO.javar, 표user의 일부 조작, 그 중에서 속성 sessionFactory는 스프링에 주입되어야 한다. 다음과 같다.

package com.lei.demo.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.lei.demo.entity.Users;

public class UsersDAO {
  private SessionFactory sessionFactory;

  public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
  }

  public SessionFactory getSessionFactory() {
    return sessionFactory;
  }

  public List<Users> getAllUser(){
    String hsql="from users";
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery(hsql);
    
    return query.list();
  }
}

UserService.java, 업무 실현 클래스, 아래

package com.lei.demo.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lei.demo.dao.*;

public class UserService {
  private UsersDAO userDao;
  
  public int userCount(){
    return userDao.getAllUser().size();
  }

  public UsersDAO getUserDao() {
    return userDao;
  }

  public void setUserDao(UsersDAO userDao) {
    this.userDao = userDao;
  }

}

우선 xml 설정,spring-hibernate를 보십시오.xml은 다음과 같습니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="
    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
    ">

  <!-- Hibernate4 -->
  <!--    , Spring , -->
  <context:property-placeholder location="classpath:persistence-mysql.properties" />
  
  <bean id="sessionFactory" 
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
      <list>
        <!--   -->
        <value>com.lei.demo.entity</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>
  
  <!--   -->
  <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.user}" />
   <property name="password" value="${jdbc.pass}" />
  </bean>
  
  <!--  Hibernate  -->
  <bean id="transactionManager"
    class="org.springframework.orm.hibernate4.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>
  
  <aop:config expose-proxy="true">
    <!--   -->
    <aop:pointcut id="txPointcut" expression="execution(* com.lei.demo.service..*.*(..))" />
    <!-- Advisor , txPointcut、txAdvice -->
    <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
  </aop:config>
  
</beans>

그 중에서 주요 설정은 tx:advice와 aop:config 두 개의 설정 섹션으로 Spring AOP 방식으로 사무 관리를 실현한다.
tx:advice는 사무의 관리자를transactionManager로 설정하였으며, tx:method는 방법명이'add*'와'get*'방법과 일치할 때 사무를 사용하도록 규정하였으며,propagation은 사무의 전파 단계를 설정합니다.'add*'와'get*'방법을 제외하고는 다른 방법의 업무는 읽기 전용입니다. (일반적으로 조회만 실행하는 업무는 이 속성을true로 설정합니다. 업데이트, 삽입, 삭제 문장이 발생하면 업무만 읽기 실패합니다.)
aop:config는 위의 advice를 인용하기 위해 aop:pointcut를 지정합니다.
이렇게 하면 AOP의 차단 메커니즘을 통해 업무를 실현할 수 있다. 물론 당신은 스프링 방식으로 사용자 DAO와 사용자 서비스를 스스로 설정해야 한다.
2. Annotation 방식
첫 번째, 우선 웹을 봅시다.xml, 다음:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://java.sun.com/xml/ns/javaee" 
  xmlns:web="http://java.sun.com/xml/ns/javaee" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    id="WebApp_ID" version="3.0">
 <display-name>Archetype Created Web Application</display-name>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:/spring-*.xml</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <servlet>
  <servlet-name>lei-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:/lei-dispatcher-servlet.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>lei-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

두 번째 단계는spring-hibernate 설정입니다. 아래spring-hibernate를 보십시오.xml 구성

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="
    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
    ">

  <!-- Hibernate4 -->
  <!--    , Spring , -->
  <context:property-placeholder location="classpath:persistence-mysql.properties" />
  
  <bean id="sessionFactory" 
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
      <list>
        <!--   -->
        <value>com.lei.demo.entity</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.user}" />
   <property name="password" value="${jdbc.pass}" />
  </bean>
  
  <!--  Hibernate  -->
  <bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
   <property name="sessionFactory" ref="sessionFactory" />
  </bean>
  
  <!--   -->
  <bean id="persistenceExceptionTranslationPostProcessor" 
    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

</beans>

제1절에서 xml 설정 업무는 tx:advice와 aop:config를 설정하여 업무의 기능을 추가해야 한다.여기에 전체 주석 방법을 채택하면 이 두 개의 설정 바이트는 필요 없다.
상응하는 필요는 보기 해석 설정에서 주석을 사용해야 합니다. 아래와 같습니다.lei-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    ">
    
  <!--    Bean(@Controller) -->
  <context:component-scan base-package="com.lei.demo" />
  
  <!--  , @Transactional , id “transactionManager”  -->
  <!--  transaction-manager , spring ,  -->
  <tx:annotation-driven transaction-manager="transactionManager"/>
  
  <!--   -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
      <value>/WEB-INF/user/</value>
    </property>
    <property name="suffix">
      <value>.jsp</value>
    </property>
  </bean>
  
</beans>

UserDAO는 다음과 같습니다.

package com.lei.demo.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.lei.demo.entity.Users;

@Repository
public class UsersDAO {
  @Resource(name="sessionFactory")
  private SessionFactory sessionFactory;

  public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
  }

  public SessionFactory getSessionFactory() {
    return sessionFactory;
  }

  public List<Users> getAllUser(){
    String hsql="from users";
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery(hsql);
    
    return query.list();
  }
}

UserService.java는 다음과 같습니다.

package com.lei.demo.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lei.demo.dao.*;

@Service("userService")
public class UserService {
  @Resource
  private UsersDAO userDao;
  
  @Transactional
  public int userCount(){
    return userDao.getAllUser().size();
  }

  public UsersDAO getUserDao() {
    return userDao;
  }

  public void setUserDao(UsersDAO userDao) {
    this.userDao = userDao;
  }

}

여기, 방법명 userCount에 @Transactional을 추가하면 이 방법이 업무를 활성화해야 한다는 것을 설명합니다.클래스 이름 User Service에 @Transactional을 추가하면 클래스의 모든 방법이 업무를 활성화합니다.
만약transactionManager가 여러 개 설치되어 있다면, 예를 들어transactionManager1과transactionManager2가 설정되어 있다면, @Transactional ("transactionManager1") 을 통해 어떤 데이터 원본을 사용하는 업무를 지정할 수 있습니다.
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기