본문 바로가기
카테고리 없음

[06.스프링+MyBatis]4.DAO 인터페이스 구현

by jaekk 2018. 8. 17.

DAO인터페이스와 Mapper의 작성이 완료됐다면 이를 구현하는 구현 클래스를 작성해야한다.

MyBatis에서 DAO를 이용하는 경우-> SqlSessionTemplate를 사용


1. SqlSessionTemplate의 설정

1) SqlSessionTemplate 클래스

2) DB 연결 및 종료 

3) mybatis-spring에서 제공

4) 트랜잭션 관리

5) 안정성: 쓰레드 처리

6) SqlSessionFactory를 생성자로 주입하여 설정


root-context.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
<?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.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
        
        
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3307/book_ex?useSSL=false"></property>
        <property name="username" value="zerock"></property>
        <property name="password" value="zerock"></property>
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" /
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    </bean>
</beans>
 
cs


2. 구현 클래스 작성

SqlSessionTemplate를 주입받아 사용

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
package org.zerock.persistence;
 
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import org.zerock.domain.MemberVO;
 
// DAO를 스프링에 인식
@Repository
public class MemberDAOImpl implements MemberDAO {
 
    private SqlSession sqlSession;
    
    private static final String namespace = "org.zerock.mapper.MemberMapper";
 
    @Override
    public String getTime() {
        // TODO Auto-generated method stub
        return sqlSession.selectOne(namespace+".getTime");
    }
 
    @Override
    public void insertMember(MemberVO vo) {
        // TODO Auto-generated method stub
        sqlSession.insert(namespace+".insertMember", vo);
    }
}
cs

@Repository

DAO를 스프링에 인식








※ 본 게시글은 코드로 배우는 스프링 웹 프로젝트 책을 참고하여 작성하였습니다.

댓글