복붙노트

[SPRING] Spring을 이용한 자동적 인 Hibernate Transaction 관리?

SPRING

Spring을 이용한 자동적 인 Hibernate Transaction 관리?

스프링 프레임 워크는 트랜잭션 처리와 어느 정도 거리가 있습니까? "Session in Spring"책을 읽은 필자는 세션 팩토리와 트랜잭션 템플릿을 XML로 설정하고 DAO에 연결함으로써 세션 및 트랜잭션 관리에 대해 걱정하지 않는 DAO 메소드를 만드는 예제를 제안했다. 반면 SpringSource.org의 문서에서는 이러한 일이 발생하기 위해 XML 및 / 또는 주석이 많이 필요하다고 제안합니다.

여기서 진실은 무엇입니까? 코드 라인을 따라 코드를 취할 수있는 가장 간단한 방법은 무엇입니까?

get session from sessionfactory
open transaction
preform database actions
commit transaction with error handling

그리고 그것을 단지 만들어라.

preform database actions

최소한 내 방법을 통해 보일러 플레이트 트랜잭션 코드의 양을 줄이십시오?

해결법

  1. ==============================

    1.Spring은 최소한 세 가지 트랜잭션 구분 방법을 제공한다.

    Spring은 최소한 세 가지 트랜잭션 구분 방법을 제공한다.

    1) 프로그래밍 방식의 처리, TransactionTemplate 또는 PlatformTransactionManager를 통한 설정 - 불빛에 대한 설정

    2) XML을 통한 선언적 - 자세한 XML이지만 비 침습적입니다.

    3) Annotation을 통한 Declarative - XML에 대한 조명

    어떤 것을 골라야하는지는 Spring이 당신에게 가장 적합한 것을 선택하는 것에 달려 있습니다. 귀하의 질문에서, 당신이 쫓고있는 주석 접근법처럼 들립니다.

    주석 참조 트랜잭션 처리의 섹션 인 Spring 참조 설명서를 읽는 것이 좋습니다. 명확하고 간결합니다.

    나는 항상 ref 문서를 먼저 참조하고 문서에없는 경우에만 책을 참조한다.

  2. ==============================

    2.당신이해야 할 일이 있습니다.하지만 그렇게할만한 것은 아닙니다. 아마도 JPA를 사용하여 자신의 공급자를 선택해야합니다. 최대 절전 모드. 그런 다음 META-INF 폴더에 지속성 단위를 정의하는 persistence.xml을 배치해야합니다.

    당신이해야 할 일이 있습니다.하지만 그렇게할만한 것은 아닙니다. 아마도 JPA를 사용하여 자신의 공급자를 선택해야합니다. 최대 절전 모드. 그런 다음 META-INF 폴더에 지속성 단위를 정의하는 persistence.xml을 배치해야합니다.

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" 
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" 
                 version="1.0">
        <persistence-unit name="YourDatabasePersistenceUnitName" transaction-type="RESOURCE_LOCAL"/>           
    </persistence>
    

    다음으로, 사용하는 Spring 애플리케이션 컨텍스트에서 데이터베이스 연결에 필요한 모든 것을 정의한다. 최소한 다음을 포함해야한다.

    <bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>/WEB-INF/jdbc.properties</value>     
            </property>
        </bean>
    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
              destroy-method="close" scope="singleton">
            <property name="driverClassName" value="org.postgresql.Driver"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
    
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="persistenceUnitName" value="YourDatabasePersistenceUnitName"/>
            <property name="dataSource" ref="dataSource"/>
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <property name="database" value="POSTGRESQL" />
                    <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
                    <property name="showSql" value="true"/>
                    <property name="generateDdl" value="false"/>
                </bean>
            </property>     
        </bean>
    
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory"/>
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
    
     <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    

    위의 일부 속성은 필요에 따라 변경되거나 추가 될 수 있습니다. 이 예제는 당신이 짐작할 수 있듯이 Hibernate와 PostgreSQL 데이터베이스가있는 JPA를위한 것입니다.

    이제 다음과 같이 데이터 액세스 메소드를 간단하게 정의 할 수 있습니다.

    @Repository
    @Transactional
    public class UserJpaDAO {
    
        protected EntityManager entityManager;
    
        @PersistenceContext
        public void setEntityManager(EntityManager entityManager) {
            this.entityManager = entityManager;
        }
    
        public void save(User theUser) {
            entityManager.persist(theUser);
        }
    
        public User update(User theUser) {
            return entityManager.merge(theUser);
        }
     }
    

    여기서 User는 애플리케이션에서 정의한 JPA 엔티티입니다. 관리자 / 컨트롤러 레이어에서 DAO를 호출하는 트랜잭션을 관리 할 수 ​​있습니다. 실제로는 그렇게합니다.하지만 예제를 너무 많이 혼란스럽게하지 않기 위해 여기에 배치했습니다.

    나의 예문 대신에 바로 가고 싶을지도 모르는 훌륭한 참고 문헌은 http://icoloma.blogspot.com/2006/11/jpa-and-spring-fucking-cooltm_26.html 참조하는 상위 3 개 링크는 함께 갈 가치가 있습니다.

  3. from https://stackoverflow.com/questions/758050/automatic-hibernate-transaction-management-with-spring by cc-by-sa and MIT license