스프링 트랜잭션 관리 – 스프링부트(Spring Boot) 기반의 프로그래밍을 통한 트랜잭션 관리 예제 실습(Transacti…

FSP 0 1,070 04.13 17:20

 

스프링 트랜잭션 관리 – 스프링부트(Spring Boot) 기반의 프로그래밍을 통한 트랜잭션 관리 예제 실습(TransactionTemplate, TransactionManager)

 

n  스프링부트 기반으로 Transactiontemplate, TransactionManager를 이용하여 소스코드에서 트랜잭션을 관리하는 예제를 작성하자.

n  Spring Starter Projectdemo-person 이라는 이름의 프로젝트를 생성하자. 패키지명은 a.b.person

n  두번째 화면에서 jdbc, mysql 선택

n  [application.properties]

 

spring.datasource.platform=mysql

spring.datasource.url=jdbc:mysql://localhost:3307/person?createDatabaseIfNotExist=true

spring.datasource.username=root

spring.datasource.password=1234

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.sql-script-encoding=UTF-8

 

n  먼저 mariaDB쪽에 person 이라는 DBperson 테이블을 생성하자.

CREATE TABLE person (

id int NOT NULL AUTO_INCREMENT,

First_Name  varchar(25) NULL,

Last_Name   varchar(25) NULL,

Street_Name varchar(25) NULL,

City        varchar(25) NULL,

State       varchar(25) NULL,

Country     varchar(25) NULL,

PRIMARY KEY (id)

);

n  [pom.xml]

 

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

 

   <groupId>com.example</groupId>

   <artifactId>demo-person-1</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>jar</packaging>

 

   <name>demo-person-1</name>

   <description>Demo project for Spring Boot</description>

 

   <parent>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-parent</artifactId>

         <version>2.0.1.RELEASE</version>

         <relativePath/> <!-- lookup parent from repository -->

   </parent>

 

   <properties>

         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

         <java.version>1.8</java.version>

   </properties>

 

   <dependencies>

         <dependency>

               <groupId>org.springframework.boot</groupId>

               <artifactId>spring-boot-starter-jdbc</artifactId>

         </dependency>

 

         <dependency>

               <groupId>mysql</groupId>

               <artifactId>mysql-connector-java</artifactId>

               <scope>runtime</scope>

         </dependency>

         <dependency>

               <groupId>org.springframework.boot</groupId>

               <artifactId>spring-boot-starter-test</artifactId>

               <scope>test</scope>

         </dependency>

   </dependencies>

 

   <build>

         <plugins>

               <plugin>

                     <groupId>org.springframework.boot</groupId>

                     <artifactId>spring-boot-maven-plugin</artifactId>

               </plugin>

         </plugins>

   </build>

 

 

</project>

 

n  [Person.java]

 

package a.b.person;

 

import java.io.Serializable;

 

public class Person implements Serializable{

 

    private static final long serialVersionUID = 1L;

    private String FirstName;

    private String LastName;

    private String street;

    private String city;

    private String state;

    private String country;

   

   

    public Person(String firstName, String lastName, String street,

        String city, String state, String country) {

    super();

    FirstName = firstName;

    LastName = lastName;

    this.street = street;

    this.city = city;

    this.state = state;

    this.country = country;

    }

   

    public String getFirstName() {

        return FirstName;

    }

    public void setFirstName(String firstName) {

        FirstName = firstName;

    }

    public String getLastName() {

        return LastName;

    }

    public void setLastName(String lastName) {

        LastName = lastName;

    }

    public String getStreet() {

        return street;

    }

    public void setStreet(String street) {

        this.street = street;

    }

    public String getCity() {

        return city;

    }

    public void setCity(String city) {

        this.city = city;

    }

    public String getState() {

        return state;

    }

    public void setState(String state) {

        this.state = state;

    }

 

    public String getCountry() {

        return country;

    }

 

    public void setCountry(String country) {

        this.country = country;

    }

   

 

}

 

n  [IPersonDAO.java]

 

package a.b.person;

 

public interface IPersonDAO {

   int insertUser(Person person);

   int insertUser2(Person person);

    void deletePerson(int personID);

    void selectAllPerson();

    void selectPersonByName();

}

 

n  [PersonDAO.java]

 

package a.b.person;

 

import java.sql.Types;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

 

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.stereotype.Repository;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.TransactionDefinition;

import org.springframework.transaction.TransactionStatus;

import org.springframework.transaction.support.DefaultTransactionDefinition;

import org.springframework.transaction.support.TransactionCallback;

import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import org.springframework.transaction.support.TransactionTemplate;

 

@Repository

public class PersonDAO implements IPersonDAO {

 

   private JdbcTemplate jdbcTemplate;

    private TransactionTemplate transactionTemplate;

    private PlatformTransactionManager txManager;

   

    @Override

    // TransactionManager 이용하여 insertUser 메소드를 구현.

    public int insertUser2(final Person person) {

         DefaultTransactionDefinition td =

                       new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);

    td.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);

         td.setTimeout(10);

         TransactionStatus status = txManager.getTransaction(td);

        

         try {

        int value = 0;

       

        for(int i=0; i<3; i++) {

               String inserQuery = "INSERT INTO person(First_Name,"

                   + " Last_Name, Street_Name, City, State, Country)"

                   + " VALUES(?, ?, ?, ?, ?, ?)";

               Object[] params = new Object[] {

                      person.getFirstName(),

                         person.getLastName(),

                         person.getStreet(), person.getCity(),

                         person.getState(),

                         person.getCountry() };

              

               int[] types = new int[] { Types.VARCHAR, Types.VARCHAR,

                   Types.VARCHAR,

                   Types.VARCHAR, Types.VARCHAR,

                   Types.VARCHAR };

               value += jdbcTemplate.update(inserQuery, params, types);

        }

           

            System.out.println("\n Person inserted to the tabl :: " + value);

            txManager.commit(status);

            return value;

        } catch (Exception e) {

        txManager.rollback(status);

        }

         return 0;

    }

 

    @Override

    public int insertUser(final Person person) {

   

    //insert statement returns results so we are using

    //TransactionCallback

    return transactionTemplate.execute(new

        TransactionCallback<Integer>() {

 

    @Override

        public Integer doInTransaction(TransactionStatus

            transactionStatus) {

        try {

        int value = 0;

       

        for(int i=0; i<3; i++) {

               String inserQuery = "INSERT INTO person(First_Name,"

                   + " Last_Name, Street_Name, City, State, Country)"

                   + " VALUES(?, ?, ?, ?, ?, ?)";

               Object[] params = new Object[] { person.getFirstName(),

                   person.getLastName(),

                   person.getStreet(), person.getCity(),

                   person.getState(),

                   person.getCountry() };

               int[] types = new int[] { Types.VARCHAR, Types.VARCHAR,

                   Types.VARCHAR,

                   Types.VARCHAR, Types.VARCHAR,

                   Types.VARCHAR };

               value += jdbcTemplate.update(inserQuery, params, types);

        }

           

            System.out.println("\n Person inserted to the tabl :: " + value);

          

            return value;

        } catch (Exception e) {

            transactionStatus.setRollbackOnly();

        }

        return 0;

        }

 

    });

   

    }

 

    @Override

    public void deletePerson(final int personID) {

   

    //delete statement doesn't returns anything so we are using

    //TransactionCallbackWithoutResult

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

 

        @Override

        protected void doInTransactionWithoutResult(TransactionStatus

            transactionStatus) {

        try {

            String deletePerson = "DELETE FROM person WHERE id =?";

            Object[] params = new Object[] { personID };

            int[] types = new int[] { Types.VARCHAR };

            jdbcTemplate.update(deletePerson, params, types);

            System.out.println("\nPerson with id 1 deleted from "

                + "the table\n");

        } catch (Exception e) {

            transactionStatus.setRollbackOnly();

        }

 

        }

 

    });

 

    }

 

    @Override

    public void selectAllPerson() {

 

    System.out.println("\nList of person in the table\n");

    String selectAllPerson = "SELECT * FROM person";

    List<Map<String, Object>> listOfPerson = jdbcTemplate.

        queryForList(selectAllPerson);

    for (Iterator<Map<String, Object>> iterator = listOfPerson.

        iterator(); iterator.hasNext();) {

        Map<String, Object> map = (Map<String, Object>)

            iterator.next();

        System.out.println(map);

    }

    System.out.println();

 

    }

   

    @Override

    public void selectPersonByName() {

 

    System.out.println("\nList of person name Java "

        + "in the table\n");

    String selectAllPerson = "SELECT * FROM person where "

        + "First_Name ='Java'";

    List<Map<String, Object>> listOfPerson = jdbcTemplate.

        queryForList(selectAllPerson);

    for (Iterator<Map<String, Object>> iterator = listOfPerson.

        iterator(); iterator.hasNext();) {

        Map<String, Object> map = (Map<String, Object>)

            iterator.next();

        System.out.println(map);

    }

    System.out.println();

 

    }

   

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

    this.jdbcTemplate = jdbcTemplate;

    }

 

    public TransactionTemplate getTransactionTemplate() {

        return transactionTemplate;

    }

 

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {

        this.transactionTemplate = transactionTemplate;

    }   

   

    public void setTxManager(PlatformTransactionManager platformTransactionManager) {

        this.txManager = platformTransactionManager;

    }

 

}

 

n  [DemoPersonApplication.java]

 

package a.b.person;

 

import javax.sql.DataSource;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.support.TransactionTemplate;

 

@SpringBootApplication

public class DemoPersonApplication implements CommandLineRunner {

 

   @Autowired

   PersonDAO personDAO;

  

   public static void main(String[] args) {

         SpringApplication.run(DemoPerson1Application.class, args);

   }

  

   @Autowired

   private JdbcTemplate jdbcTemplate;

  

   @Autowired

   private DataSource dataSource;

  

   @Bean

    public PlatformTransactionManager transactionManager(DataSource dataSource)

    {

        return new DataSourceTransactionManager(dataSource);

    }

 

   @Override

   public void run(String... args) throws Exception {

         personDAO.setJdbcTemplate(jdbcTemplate);

         personDAO.setTransactionTemplate(new TransactionTemplate(transactionManager(dataSource)));

         personDAO.setTxManager(transactionManager(dataSource));

        

         Person person = new Person("Java", "Honk",

                 "John st.","NY", "NY", "USA");

            

             //Insert user to the table 3 times:            

             personDAO.insertUser(person);  

            

             //Insert user to the table 3 times:            

             personDAO.insertUser2(person); 

            

             //Delete first person from table

             personDAO.deletePerson(1);

                

             //Select all inserted user from the table

             personDAO.selectAllPerson();   

            

             //Select data from tabel where person

             //name is "Java"

             personDAO.selectPersonByName();

        

   }

}

 


 

Comments