경제학도의 개발공간

[20180508]Mybatis_Transaction 본문

카테고리 없음

[20180508]Mybatis_Transaction

reallifeliver 2018. 5. 8. 10:05
반응형
1
2
@Service
public class CustomerService {
cs


@Service라는 Annotation을 붙히게 되면 bean 객체를 만들지 않아도


1
<context:component-scan base-package="ncontroller" />
cs


이라는 태그를 통해 자동 객체를 생성할 수 있다 .




기존 모델에서 우리는 Controller에서 URl Mapping과 클라이언트 요청을 해결하기 위한 DB작업 및 VIEW의 지정 등의 모든 작업을 진행하였다. 이제는 Service라는 패키지와 하위 class들을 작성해 DB작업을 위임하는 작업을 진행해 본다.


이제는 Controller에서는 Service객체만을 필요로 하며, 기존 존재하던 SqlSession객체는 Service class로 이동하게 된다 .



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Controller
@RequestMapping("/customer/")
public class CustomerController {
 
    @Autowired
    private CustomerService customerservice;
        
    //글 목록보기
    
    @RequestMapping("notice.htm")
    public String notices(String pg , String f , String q , Model model) throws ClassNotFoundException, SQLException {
        
        List<Notice> list = customerservice.notices(pg, f, q);
        model.addAttribute("list", list);
        
        return "customer.notice";
    }
cs



이렇게 Service과 Controller를 분리하면 이제 본격적으로 Transation에 대한 개념을 알아보자 





 Transacion이란?



물리적으로 여러개의 작업이지만 결과적으로는 하나의 작업



트랜잭션을 처리하기 위해서는 xml 구성은 다음과 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" 추가
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
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx.xsd"> 추가
 
 
 <bean id="driverManagerDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
   <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"></property>
   <property name="username" value="springuser"></property>
   <property name="password" value="1004"></property>
 </bean>
 
 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
   <property name="dataSource" ref="driverManagerDataSource" />
 </bean>
   
 <!-- 공통빈 -->
 <bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
            <property name="maxUploadSize" value="10485760"/>
 </bean>
 
  <!-- Transaction 만들기 -->
  <bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="driverManagerDataSource" />
  </bean>
 
  <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
cs



<tx:annotation-driven transaction-manager="transactionManager"/> @Transactional 이 붙어 있는 요청에 대한 검증을 한다.





아래는 Service에 있는 하나의 함수에 Transactional을 걸어 두면, 그 안에 있는 어떤 요청에서라도 예외가 발생할 경우 자동으로 Rollback처리가 나도록 설정한 코드이다




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@Transactional
    public String noticeReg(Notice n, HttpServletRequest request)
            throws ClassNotFoundException, SQLException, IOException {
 
        List<CommonsMultipartFile> files = n.getFiles();
        List<String> filenames = new ArrayList<>(); // 파일명만 추출
        if (files != null && files.size() > 0) {
            for (CommonsMultipartFile mutifile : files) {
                String filename = mutifile.getOriginalFilename();
                String path = request.getServletContext().getRealPath("/customer/upload");
                String fpath = path + "\\" + filename;
                System.out.println(filename + " , " + fpath);
                if (!filename.equals("")) {
                    FileOutputStream fs = new FileOutputStream(fpath);
                    fs.write(mutifile.getBytes());
                    fs.close();
                }
                filenames.add(filename);
            }
        }
 
        n.setFileSrc(filenames.get(0));
        n.setFileSrc2(filenames.get(1));
 
        NoticeDao noticedao = sqlsession.getMapper(NoticeDao.class);
        // 기존 코드
        // noticedao.insert(n);
 
        // 트랜잭션 적용코드 (게시판 글쓰기 하면 회원에게 POINT 1점 추가 : constraint ck_member_hit check(point
        // < 3)
        try {
            noticedao.insert(n); // 게시판 글쓰기
            noticedao.insertOfMemberPoint("test");
            System.out.println("board insert , member point update");
        } catch (Exception e) {
            System.out.println("Transaction 예외 발생" + e.getMessage());
            throw e; // 예외 발생 시기면 : 자동 rollback
        }
 
        return "redirect:notice.htm";
    }
cs
























반응형