티스토리 뷰

spring 설정파일도 이제 잘 만들었겠다. MyBais 로 잘 조회해서 결과를 가져오기만 하면 된다.

단순한 select 문을 실행해서 결과를 가져오는게 오늘의 목표. 사실 spring 설정파일만 제대로 추가 했다면 별로 할게 없다.

 

원래 가지고 있던 ExampleService 클래스를 아래와 같이 작성하자.

package com.spring.sample;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ExampleService implements Service {
    
    @Autowired
    private SqlSession sqlSession;
    
    public String getMessage() {
        HashMap<String, String> input = new HashMap<String, String>();
        input.put("code", "AIA");
        
        List<HashMap<String, String>> outputs 
            = sqlSession.selectList("SqlSampleMapper.selectSample", input);
        
        return outputs.toString();
    }
}

14 라인 : ExampleService 클래스의 멤버변수로 SqlSession 형이 있다. @Autowired 로 매핑만 해주면 SqlSessionFactory 객체를 가지고 있지 않아도 SqlSession 객체를 가져올 수 있다. 왜냐면 우린 저번에 환경설정을 잘~ 해줬기 때문이다.

어쨋든 우린 sql 문을 실행할 SqlSession 객체를 손쉽게 얻었으므로 간단히 쿼리만 날려주면 된다.

21 라인 : SqlSession 객체에서 조회결과를 리스트로 돌려주는 selectList 를 사용하며, 입력값 역시 잘 넣어준다.

23 라인 : 뭐 우리가 결과를 가지고 지금 뭘 할게 아니니 toString 함수로 값들이 잘 들어가 있는지만 확인만 해보겠다.

 

이제 테스트코드에서 실행하면 된다.

package com.spring.sample;
 
import static org.junit.Assert.assertNotNull;
 
import com.spring.sample.Service;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ExampleConfigurationTests {
     
    private Log log = LogFactory.getLog(getClass());
     
    @Autowired
    @Qualifier("exampleService")
    private Service service;
 
    @Test
    public void testSimpleProperties() throws Exception {
        assertNotNull(service);
        log.info(this.service.getMessage());
    }
}

22 라인 : Service 타입으로 등록한 Bean 들이 다수이므로 @Autowired 만 사용해서는 예외발생하며, @Qualifier 로 특정 Bean 을 명시해주면 된다.

28 라인 : JUnit 이 익숙치 않으신분들은 생소한 메소드 이지만.. service 변수가 null 이 아닌지 확인하는 테스트 함수이다.

 

테스트 코드 실행하실 때 ExampleConfigurationTest.java 를 열어놓고 문서 아무데서나 오른쪽 클릭해서 아래 그림처럼 JUnit Test 로 실행하면 된다.

 






반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함