Spring JUnit(단위 테스트), MyBatis
<오늘 배운 것>
1. JUnit 이용해 유닛 테스트하는 법
2. lazyLuke 이용해 test log 남기기
3. MyBatis 설정법
1. 유닛 테스트하기
1) 테스트 클래스 만들기
2) root-context.xml 위치 잡아준 후 테스트할 객체 주입
1
2 |
@Inject
private DataSource dataSource; |
cs |
<DataSourceTest.java>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
//junit의 test는 springFramework를 다 돌리지 않기 때문에
//의존성 주입을 해주는 context를 같이 돌린다고 명시해야 한다.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*-context.xml"})//**: 모든 폴더
public class DataSourceTest {
@Inject
private DataSource dataSource;
//@Test는 jUnit 기술이다.
@Test
public void testDataSource() throws Exception{
//통신과 같이 열어주는 클래스 생성시 try()에 넣으면 자동으로 try catch 종료시 close한다.
try(Connection conn = dataSource.getConnection()){
System.out.println(conn);
}catch(Exception e){e.printStackTrace();
}
}
}
|
cs |
3) 테스트할 부분을 @Test 안에 넣는다.
4) Run as > JUnit Test 실행
2. lazyluke 이용해 test log 남기기
1) 라이브러리 가져오기
<pom.xml>
1 2 3 4 5 6 7 8 9 10 11 | <!-- lazyluke : log4j를 이용해서 DB 내역을 log로 남기는 기술 --> <!-- dataSource를 session으로 넘길 때 가로채서 로그를 남긴다. --> <!-- https://mvnrepository.com/artifact/org.lazyluke/log4jdbc-remix --> <dependency> <groupId>org.lazyluke</groupId> <artifactId>log4jdbc-remix</artifactId> <version>0.2.7</version> </dependency>
| cs |
2) log4jdbc 주입 준비
<root-context.xml>
1 2 3 4 5 6 7 8 9 10 11 | <bean id="dataSource" class="net.sf.log4jdbc.Log4jdbcProxyDataSource"> <constructor-arg ref="dbSource"/> <property name="logFormatter"> <bean class="net.sf.log4jdbc.tools.Log4JdbcCustomFormatter"> <property name="loggingType" value="MULTI_LINE"></property> <property name="sqlPrefix" value="SQL ::"></property> </bean> </property> </bean> | cs |
3) log 출력할 클래스 지정
1 2 3 4 5 6 7 8 9 10 | <!-- Application Loggers --> <!-- log 역시 객체이기 때문에 test를 위해서 System을 계속 호출하면 메모리/System에 부하가 걸린다. --> <!-- 이런 로그 객체를 log4j가 관리해줌으로써 System에 부하를 줄인다. --> <!-- log를 남길 패키지를 지정하면 자동으로 로그 객체를 관리해준다. --> //log 출력할 클래스 위치 <logger name="com.spring.controller"> <level value="info" /> </logger> | cs |
4) lazyluke log도 출력하는 법
1 2 3 4 5 6 7 | <!-- Root Logger --> <root> <priority value="info" /> <!-- warn을 info로 수정 --> <appender-ref ref="console" /> </root> | cs |
5) System.out.println 비슷하게 log 출력하기
1 2 3 | private static final Logger logger = LoggerFactory.getLogger(HomeController.class); logger.info("==================list.do start=============="); logger.info("==================list.do end=============="); | cs |
모두 끝내면 이제 다음과 같은 log가 출력되게 됨
3. MyBatis 설정하기
MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs(Plain Old Java Objects) to database records.
간단하게 요약하면,
'SQL 관리와 결과 가져오기를 편리하게 해주는 프레임워크'
<MyBatis 사용법>
1) 라이브러리 받기
2) mapper에 쿼리 작성
3) 쿼리 실행 준비(sessionFactory, sqlSession)
4) 쿼리 실행( sqlSession.select(mapper 위치) )
1) 라이브러리 받아오기
<pom.xml>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
|
cs |
2) mapper에 쿼리 작성
<memberMapper.xml>
1
2
3
4
5
6
7
8
9
10
11
12 |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
//namespace(mapper의 위치), resultType(결과값이 들어갈 bean)
<mapper namespace="com.spring.mappers.MemberMappers">
<select id="selectTest" resultType="com.spring.vo.Member">
SELECT * FROM MEMBER WHERE NUM=#{NUM}
</select>
</mapper>
|
cs |
3) 쿼리를 실행할 준비
<root-context.xml>
1
2
3
4
5
6
7
8
9
10
11
12
13 |
<!-- 1) namespaces에 mybatis-spring 등록 -->
<!-- 2) value = xml 파일, ref = bean 객체 -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:com/spring/mappers/*Mapper.xml"></property>
</bean>
<!-- sqlSession은 실제로 쿼리를 실행하는 객체, close와 예외처리를 자동으로 해준다. -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
<constructor-arg ref="sessionFactory"/>
</bean>
|
cs |
1 2 3 4 5 6 7 8 | @RequestMapping(value="/updateForm.do", method=RequestMethod.GET) public String updateForm(int num, Model model){ Member mem = dao.detailMember(num); model.addAttribute("mem",mem); return "member/MemberUpdateForm"; } | cs |
5) DAO 메소드 실행
1 2 3 4 | @Inject SqlSession sqlSession; private final static String MemberMapper = "com.spring.mappers.MemberMappers"; | cs |
1 2 3 4 5 6 | //row 1줄은 selectOne, List는 selectList로 받음 //update는 update(), insert는 insert()를 사용 public Member detailMember(int num){ Member mem = sqlSession.selectOne(MemberMapper+".detailMember",num); return mem; } | cs |