[Spring] Spring에서 Mybatis사용하기

Sql Session이 Interface이기 때문에 Spring이랑 연동하기 위해서는 Mybatis와 Spring을 연결해주는 API를 

Spring Container에 등록해서 사용해야한다. 트랜잭션 처리는 Spring 트랜잭션이 담당한다.

 

Sql Session - (API설정 후) SqlSessionTemplate

Sql SessionFactory - (API설정 후) SqlSessionFactoryBean = <Mybatis설정파일, DataSource>


  ServiceImpl

       ↑

    DAOImpl

       ↑

SqlSessionTemplate

1.생성자 (변수 : SqlSessionFactory


       ↑

SqlSessionFactoryBean ( setter사용 )

1.dataSource

2.configLocation - mybatis 전역 설정 파일 위치


       ↑

BasicDataSource

1.driverClassName

2.username

3.password

4.maxTotal




applicationContext.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.xsd">


<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">

<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/>

  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>

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

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

  <property name="maxTotal" value="50"/>

</bean>


<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="configLocation" value="com/domain/config/mybatis-config.xml"/>

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

</bean>


<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">

<constructor-arg ref="sqlSession"/>

</bean>


<bean name="memberDao" class="com.domain.member.dao.impl.MemberDaoImpl">

<constructor-arg ref="sqlSessionTemplate"/>

</bean>


<bean name="memberService" class="com.domain.member.service.impl.MemberServiceImpl">

<constructor-arg ref="memberDao"/>

</bean>

</beans>



pom.xml


<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>MemberManager-mybatis-spring</groupId>

  <artifactId>MemberManager-mybatis-spring</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <build>

    <sourceDirectory>src</sourceDirectory>

    <resources>

      <resource>

        <directory>src</directory>

        <excludes>

          <exclude>**/*.java</exclude>

        </excludes>

      </resource>

    </resources>

    <plugins>

      <plugin>

        <artifactId>maven-compiler-plugin</artifactId>

        <version>3.5.1</version>

        <configuration>

          <source>1.8</source>

          <target>1.8</target>

        </configuration>

      </plugin>

    </plugins>

  </build>

  <properties>

  <spring.version>4.3.9.RELEASE</spring.version>

  <mybatis.version>3.4.4</mybatis.version>

  <mybatis.spring.version>1.3.1</mybatis.spring.version>

  </properties>

  <dependencies>

  <!-- 

  spring 라이브러리- 패키지 버전이 동일해야 하고 버전이 바뀌었을때 유지보수하기 편하다

  spring-context

  spring-jdbc

   -->

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-context</artifactId>

    <version>${spring.version}</version>

</dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-jdbc</artifactId>

    <version>${spring.version}</version>

</dependency>

  <!-- 

   Mybatis 라이브러리

   Mybatis, mybatis-spring 연동   

   -->

   <dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis</artifactId>

    <version>${mybatis.version}</version>

</dependency>

   <dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis-spring</artifactId>

    <version>${mybatis.spring.version}</version>

</dependency>

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-dbcp2</artifactId>

    <version>2.1.1</version>

</dependency>

  </dependencies>

</project>



MemberDaoImpl


package com.domain.member.dao.impl;


import java.util.List;


import org.mybatis.spring.SqlSessionTemplate;


import com.domain.member.dao.MemberDao;

import com.domain.member.vo.Member;



public class MemberDaoImpl implements MemberDao {

//Spring Container에서 SqlSessionTemplate을 (주입) 받아서 instance변수로 대입


private SqlSessionTemplate session;   //instance변수

public MemberDaoImpl(SqlSessionTemplate session) {  //주입받을 생성자 생성

this.session = session;

}

private String makeSql(String tagId){

return "member."+tagId;

}

@Override

public int insertMember(Member member) {

return session.insert(makeSql("insertMember"), member);

}


@Override

public int updateMemberById(Member member) {

return session.update(makeSql("updateMemberById"), member);

}


@Override

public int deleteMemberById(String memberId) {

return session.delete(makeSql("deleteMemberById"), memberId);

}


@Override

public Member selectMemberById(String memberId) {

return session.selectOne(makeSql("selectMemberById"), memberId);

}


@Override

public List<Member> selectMemberByName(String memberName) {

return session.selectList(makeSql("selectMemberByName"), memberName);

}


@Override

public List<Member> selectMemberList() {

return session.selectList(makeSql("selectMemberList"));

}


}



MemberServiceImpl


package com.domain.member.service.impl;


import java.util.List;


import com.domain.common.exception.DuplicatedIdException;

import com.domain.common.exception.MemberNotFoundException;

import com.domain.member.dao.MemberDao;

import com.domain.member.service.MemberService;

import com.domain.member.vo.Member;



public class MemberServiceImpl implements MemberService {


private MemberDao dao;  //instance 변수

public MemberServiceImpl(MemberDao dao){  //주입받을 생성자 생성

this.dao = dao;

}


@Override

public void addMember(Member member) throws DuplicatedIdException {

if(dao.selectMemberById(member.getId())!=null){

throw new DuplicatedIdException(member.getId()+" 는 이미 등록된 ID");

}

dao.insertMember(member);

}


@Override

public void removeMemberById(String id) throws MemberNotFoundException {

if(dao.selectMemberById(id)==null){

throw new MemberNotFoundException(String.format("ID %s 인 회원이 없습니다.", id));

}

dao.deleteMemberById(id);

}


@Override

public void updateMember(Member newData) throws MemberNotFoundException {

if(dao.selectMemberById(newData.getId())==null){

throw new MemberNotFoundException(String.format("ID %s 인 회원이 없습니다.", newData.getId()));

}

dao.updateMemberById(newData);


}


@Override

public Member findMemberById(String id) {

return dao.selectMemberById(id);

}


@Override

public List<Member> findMemberByName(String name) {

return dao.selectMemberByName(name);

}


@Override

public List<Member> getMemberList() {

return dao.selectMemberList();

}


}




'BACKEND > Spring' 카테고리의 다른 글

[Spring] Spring MVC 개념  (0) 2017.06.16
[Spring] Spring MVC 예제  (0) 2017.06.15
[Spring] Transaction  (0) 2017.06.15
[Spring] AOP  (0) 2017.06.14
[Spring] Spring 개념 자료  (0) 2017.06.13

댓글

Designed by JB FACTORY