MyBatis 연동을 mapper 인터페이스 기반으로 변경



=>인터페이스를 생성하고 메소드 위에 Sql을 작성합니다. 

=> DAO 클래스를 만들지 않아도 됩니다. 



1.SQL을 실행할 수 있는 GoodMapper 인터페이스를 생성하고 메소드를 생성 


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
package com.tistory.tstigma.dao;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import com.tistory.tstigma.domain.Sawon;
 
public interface SawonMapper {
 
    
//sawon 테이블의 전체 데이터를 가져오는 메소드
    @Select("select * from sawon")
    public List<Sawon> allsawon();
    
    //데이터를 삽입하는 메소드 
    @Insert("insert into sawon values (sawonseq.nextval, #{name},#{email},#{tel},#{address})")
    public void insertsawon(Sawon sawon);
    
    //데이터를 수정하는 메소드 
    @Update("update sawon set name=#{name}, email=#{email}, tel=#{tel}, address=#{address} where bunho=#{bunho}")
    public void updatesawon(Sawon sawon);
    
    //데이터를 삭제하는 메소드
    @Delete("delete sawon where bunho=#{bunho}")
    public void deletesawon(Integer bunho);
    
    //name이 포함된 데이터를 찾아오는 메소드 
    @Select("select * from sawon where lower(trim(name)) like '%' || #{name} || '%'")
    public List<Sawon> getsawon(String name);
}
 
cs


2.application Context.xml 파일에서 myBatis 연동 객체 만드는 부분을 수정 


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
42
43
44
45
46
47
48
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
 
 
 
     <!-- 어노테이션을 프로젝트에서 사용할 수있도록 설정   -->
    <context:annotation-config/>
    
    <!-- 패키지 안에 있는 클래스들 중에서 어노테이션이 붙은 클래스들의 bean을 자동 생성해주는 설정  -->
    <context:component-scan base-package="com.tistory.tstigma"></context:component-scan>
    
    <!-- 데이터 베이스 접속 정보를 저장 DataSource 클래스의 bean -->
    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <!-- 접속할 데이터베이스 종류  -->
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@192.168.0.200:1521:xe"/>
        <property name="username" value="user08"/>
        <property name="password" value="user08"/>
    </bean>
 
 
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id ="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
    </bean>
 
 
    <!-- Sql이 작성되어 있는 인터페이스를 등록 -->
    <bean id="goodMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" value="com.tistory.tstigmg.dao.SawonMapper"></property>
    </bean>
 
 
    <!-- 실제 mybatis 운영을 위한 클래스의 bean -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
 
    
 
</beans>
cs


3 Main에서 실행 


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
42
43
44
45
46
47
 
 
dao     /*@Autowired*/ 주석처리 
 
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
import com.tistory.tstigma.dao.SawonDao;
import com.tistory.tstigma.dao.SawonMapper;
 
public class Main {
 
    public static void main(String[] args) {
 
        
        GenericXmlApplicationContext context = 
                new GenericXmlApplicationContext(
                        "classpath:applicationContext.xml");
        
        SawonMapper dao = context.getBean(SawonMapper.class);
        
    
        System.out.println(dao.allsawon());
        
        
        /*    
        Sawon sawon = new Sawon();
        sawon.setName("아이린");
        sawon.setEmail("red@naver.com");
        sawon.setTel("010");
        sawon.setAddress("청담동");
        dao.insertsawon(sawon);
    
        //데이터 수정 
        Sawon sawon2 = new Sawon();
        
        sawon2.setBunho(4);
        sawon2.setName("배수지");
        sawon2.setEmail("bae@gmail.com");
        sawon2.setTel("011");
        sawon2.setAddress("광주");
        dao.updatesawon(sawon2);
        
        */
        context.close();
    }
}
cs




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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
**xml 기반의 MyBatis 연동을 mapper 인터페이스 기반으로 변경
=>인터페이스를 생성하고 메소드 위에 SQL을 작성합니다.
=>Dao 클래스를 만들지 않아도 됩니다.
 
1.SQL을 실행할 수 있는 GoodMapper 인터페이스를 생성하고 메소드를 생성
package kr.co.pk.dao;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import kr.co.pk.domain.Sawon;
 
public interface SawonMapper {
    //sawon 테이블의 전체 데이터를 가져오는 메소드
    @Select("select * from sawon")
    public List<Sawon> allsawon();
    
    //데이터를 삽입하는 메소드 - 리턴타입 정수
    @Insert("insert into sawon values("
            + "#{bunho}, #{name}, #{email}, #{tel}, #{address}")
    public int insertsawon(Sawon sawon);
    //데이터를 수정하는 메소드 - 리턴타입 정수
    @Update("update sawon "
            + "set name=#{name}, email=#{email}, tel=#{tel}, "
            + "address=#{address} "
            + "where bunho=#{bunho}")
    public int updatesawon(Sawon sawon);
    
    //데이터를 삭제하는 메소드 - 리턴타입 정수
    @Delete("delete from sawon where bunho=#bunho")
    public int deletesawon(Integer bunho);
    
    //name이 포함된 데이터를 찾아오는 메소드
    @Select("select * from sawon where name = '%'||#{name}||'%'")
    public List<Sawon> getsawon(String name);
}
 
2.applicationContext.xml 파일에서 MyBatis 연동 객체 만드는 부분을 수정
    <!-- MyBatis 설정 내용을 저장하고 있는 클래스의 bean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- sql이 작성되어 있는 인터페이스를 등록 -->
    <bean id="goodMapper" 
        class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" 
            value="kr.co.pk.dao.SawonMapper" />
    </bean>
 
3.main 메소드에서 테스트
GenericXmlApplicationContext context = 
            new GenericXmlApplicationContext(
                "classpath:applicationContext.xml");
        SawonMapper dao = context.getBean(SawonMapper.class);
        System.out.println(dao.allsawon());
 
cs


'Java > 스프링' 카테고리의 다른 글

파일다운로드 방법  (0) 2018.04.19
mybatis 연결할 때 한번보기 위해 저장  (0) 2018.04.13
스프링 Mybatis를 XML DB 연결  (0) 2018.04.12
JdbcTemplate 클래스  (0) 2018.04.09
Spring 2-2 TEST 디렉토리 사용  (0) 2018.04.09

+ Recent posts