반응형

Spring Programmatic Transaction Management


(원문 위치 : http://www.tutorialspoint.com/spring/programmatic_management.htm )

프로그램적 트랜젝션 관리 접근은 소스코드에서 프로그램을 이용하여 트랜젝션을 관리하는 것을 허용한다. 이는 엄청나게 유연함을 제공하지만, 유지보수가 어렵다.

시작하기 전에 트랜젝션을 사용하여 다양한 CRUD 작업을 수행할 수 있는 두개의 데이터베이스 테이블이 있어야 한다. 아래와 같이 Student table(이미 생성해 놓은)과
CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);
두번째 학년에 기초한 학생에 대한 표식(mark)를 관리(maintain)할 Marks을 Student table에 대해 아래와 같이 foreign key를 갖도록 만든다.
CREATE TABLE Marks(
   SID INT NOT NULL,
   MARKS  INT NOT NULL,
   YEAR   INT NOT NULL
);
프로그램적 접근이 트랜젝션을 구현하는 것을 구현하기 위하여 직접적으로 PlatformTransactionManager를 사용하자. 새로운 트랜젝션을 시작하기 위해 적절한 트랜젝션 속성(attribute)로 TransactionDefinition의 인스턴스를 가질 필요가 있다. 이번 예제는 기본 트랜젝션 속성(attribute)을 사용하기 위해 DefaultTransactionDefinition의 인스턴스를 생성할 것이다.

TransactionDefinition이 생성된 후 TransactionStatus의 인스턴스를 반환하는 getTransaction() 함수를 호출함으로써 transaction을 시작할 수 있다. TransactionStatus 객체는 transaction의 현재 상태와 최종적으로 모든것이 잘 되었다면 transaction을 commit하기 위해 PlatformTransactionManager의 commit()함수를 사용할 수 있고, 반대라면 rollback()을 사용할 수 있다.

이제 Student와 Marks 테이블에 간단한 명령(operation)을 구현하는 Spring JDBC 프로그램을 작성해 보자.

[003] HelloWorld Example 강좌를 참조하여 프로젝트를 생성한다.

POM.xml아래의 의존관계를 추가한다.(jdbc사용과 mariadb접속을 위한 의존관계 추가이다. 다른DB를 이용한다면 해당 의존관계를 추가해야 한다.)

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>3.2.4.RELEASE</version>

</dependency>


<dependency>

<groupId>org.mariadb.jdbc</groupId>

<artifactId>mariadb-java-client</artifactId>

<version>1.1.7</version>

</dependency>


StudentMarks.java:

package com.tutorialspoint;


public class StudentMarks {

private Integer age;

private String name;

private Integer id;

private Integer marks;

private Integer year;

private Integer sid;

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public Integer getMarks() {

return marks;

}

public void setMarks(Integer marks) {

this.marks = marks;

}

public Integer getYear() {

return year;

}

public void setYear(Integer year) {

this.year = year;

}

public Integer getSid() {

return sid;

}

public void setSid(Integer sid) {

this.sid = sid;

}

}


StudentDAO.java:

package com.tutorialspoint;


import java.util.List;


import javax.sql.DataSource;


public interface StudentDAO {

  /** 

    * This is the method to be used to initialize

    * database resources ie. connection.

    */

  public void setDataSource(DataSource ds);

  /** 

    * This is the method to be used to create

    * a record in the Student and Marks tables.

    */

  public void create(String name, Integer age, Integer marks, Integer year);

  /** 

    * This is the method to be used to list down

    * all the records from the Student and Marks tables.

    */

  public List<StudentMarks> listStudents();

}



StudentMarksMapper.java:

package com.tutorialspoint;


import java.sql.ResultSet;

import java.sql.SQLException;


import org.springframework.jdbc.core.RowMapper;


public class StudentMarksMapper implements RowMapper<StudentMarks> {


@Override

public StudentMarks mapRow(ResultSet arg0, int arg1) throws SQLException {

// TODO Auto-generated method stub

//return null;

StudentMarks studentMarks = new StudentMarks();

studentMarks.setId(arg0.getInt("id"));

studentMarks.setName(arg0.getString("name"));

studentMarks.setAge(arg0.getInt("age"));

studentMarks.setSid(arg0.getInt("sid"));

studentMarks.setMarks(arg0.getInt("marks"));

studentMarks.setYear(arg0.getInt("year"));

return studentMarks;

}


}



StudentJDBCTemplate.java:

package com.tutorialspoint;


import java.sql.Types;

import java.util.List;


import javax.sql.DataSource;


import org.springframework.dao.DataAccessException;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.TransactionDefinition;

import org.springframework.transaction.TransactionStatus;

import org.springframework.transaction.support.DefaultTransactionDefinition;


public class StudentJDBCTemplate implements StudentDAO {


private DataSource dataSource;

private JdbcTemplate jdbcTemplateObject;

private PlatformTransactionManager transactionManager;

@Override

public void setDataSource(DataSource ds) {

// TODO Auto-generated method stub

this.dataSource = ds;

this.jdbcTemplateObject = new JdbcTemplate(ds);

}

public void setTransactionManager(PlatformTransactionManager transactionManager) {

this.transactionManager = transactionManager;

}


@Override

public void create(String name, Integer age, Integer marks, Integer year) {

// TODO Auto-generated method stub

TransactionDefinition def = new DefaultTransactionDefinition();

TransactionStatus status = transactionManager.getTransaction(def);

try {

Object[] params;

int[] types;

params = new Object[]{name, age};

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

String SQL1 = "insert into Student (name, age) values (?, ?)";

jdbcTemplateObject.update(SQL1, params, types);


// Get the lastest student id to be used in Marks table

String SQL2 = "select max(id) from Student";

int sid = jdbcTemplateObject.queryForInt(SQL2);

params = new Object[]{sid, marks, year};

types = new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};

String SQL3 = "insert into Marks (sid, marks, year) " +

             "values (?, ?, ?)";

jdbcTemplateObject.update(SQL3, params, types);

System.out.println("Created Name = " + name 

+ ", Age = " + age);

transactionManager.commit(status);

} catch(DataAccessException e) {

System.out.println("Error in creating record, rolling back");

transactionManager.rollback(status);

throw e;

}

return;

}


@Override

public List<StudentMarks> listStudents() {

// TODO Auto-generated method stub

//return null;

String SQL = "select * from Student, Marks " +

            " where Student.id = Marks.sid";

List<StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, new StudentMarksMapper());

return studentMarks;

}


}





MainApp.java:

package com.tutorialspoint;


import java.util.List;


import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MainApp {

public static void main(String[] args) {

ApplicationContext context

new ClassPathXmlApplicationContext("Beans.xml");

StudentJDBCTemplate studentJDBCTemplate

(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

System.out.println("-----Records creation-----");

studentJDBCTemplate.create("Zara", 11, 99, 2010);

studentJDBCTemplate.create("Nuha", 20,  97,  2010);

studentJDBCTemplate.create("Ayan", 25, 100, 2011);

System.out.println("-----Listing all the records-----");

List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();

for(StudentMarks record : studentMarks) {

        System.out.print("ID : " + record.getId() );

        System.out.print(", Name : " + record.getName() );

        System.out.print(", Marks : " + record.getMarks());

        System.out.print(", Year : " + record.getYear());

        System.out.println(", Age : " + record.getAge());

}

}

}


Beans.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-3.0.xsd ">


   <!-- Initialization for data source -->

   <bean id="dataSource" 

      class="org.springframework.jdbc.datasource.DriverManagerDataSource">

      <property name="driverClassName" value="org.mariadb.jdbc.Driver"/>

      <property name="url" value="jdbc:mariadb://10.211.55.23:3306/TestDB"/>

      <property name="username" value="root"/>

      <property name="password" value="dba"/>

   </bean>


   <!-- Initialization for TransactionManager -->

   <bean id="transactionManager" 

      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

      <property name="dataSource"  ref="dataSource" />    

   </bean>


   <!-- Definition for studentJDBCTemplate bean -->

   <bean id="studentJDBCTemplate"

      class="com.tutorialspoint.StudentJDBCTemplate">

      <property name="dataSource"  ref="dataSource" />

      <property name="transactionManager"  ref="transactionManager" />    

   </bean>

      

</beans>



실행 결과는 아래와 같다.

------Records creation--------
Created Name = Zara, Age = 11
Created Name = Nuha, Age = 20
Created Name = Ayan, Age = 25
------Listing all the records--------
ID : 1, Name : Zara, Marks : 99, Year : 2010, Age : 11
ID : 2, Name : Nuha, Marks : 97, Year : 2010, Age : 20
ID : 3, Name : Ayan, Marks : 100, Year : 2011, Age : 25



반응형

+ Recent posts