1. mvn > mybatis 3.4.1 버전 디펜던시 추가
https://mvnrepository.com/artifact/org.mybatis/mybatis/3.4.1
2. mvn > mybatis-spring 1.3.0 버전 디펜던시 추가
https://mvnrepository.com/artifact/org.mybatis/mybatis-spring/1.3.0
3. mvn > Spring JDBC 4.3.8 버전 디펜던시 추가
https://mvnrepository.com/artifact/org.springframework/spring-jdbc/4.3.8.RELEASE
버전 부분만 저렇게 변수 사용하는 것처럼 바꿔주기
4. mvn > Spring Transaction 4.3.8 버전 디펜던시 추가
https://mvnrepository.com/artifact/org.springframework/spring-tx/4.3.8.RELEASE
버전 변수로 바꿔주기
5. root-context.xml > Namespaces 체크
6. root-context.xml > bean 추가
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property> <!-- ref : 참조, 어디를 가리키고 있는 것 -->
</bean>
설명
인터페이스는 컴마구분으로 여러개를 받을 수 있다.
// 롬복 라이브러리 미사용할 경우
// @Autowired // 얘를 더 익숙하게 볼것이다
// private DataSource dataSource;
7. DataSourceTest > 코드작성
package com.smart.hrd;
import static org.junit.Assert.*;
import java.sql.Connection;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
// 지정한 클래스를 이용해 테스트 메서드를 수행하도록 지정해주는 어노테이션
@RunWith(SpringJUnit4ClassRunner.class)
// 지정된 클래스나 문자열을 이용해서 필요한 객체들을 스프링 내에 객체로 등록
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
// 롬복을 이용해서 로그를 기록하는 Logger 변수를 생성
@Log4j
public class DataSourceTest {
// 롬복 라이브러리 미사용할 경우
// @Autowired // 얘를 더 익숙하게 볼것이다
// private DataSource dataSource;
// @Setter : 롬복 라이브러리를 이용해 setter를 자동으로 만들어 주는 어노테이션
// @Autowired : *인스턴스 변수 에 알맞은 타입의 객체를 자동으로 주입해주는 어노테이션
// *인스턴스 변수 = dataSource
@Setter(onMethod_ = { @Autowired })
private DataSource dataSource;
@Setter(onMethod_ = { @Autowired })
private SqlSessionFactory sqlSessionFactory;
@Test
public void testConnection() {
try (SqlSession session = sqlSessionFactory.openSession();
Connection con = dataSource.getConnection()) {
log.info(sqlSessionFactory);
log.info(con);
} catch (Exception e) {
fail("Not yet implemented");
}
}
}
8. resouces > xml 파일 선택 > mybatis-config 파일 생성
mybatis-config 파일 생성
https://mybatis.org/mybatis-3/ko/getting-started.html 접속
MyBatis – 마이바티스 3 | 시작하기
mybatis.org
쭉내려서
복사
붙여넣기
9. root-context.xml > sqlSessionFactory bean 에 property 추가
<property name="configLocation" value="classpath:/mybatis-config.xml"></property> <!-- SqlSessionFactoryBean.class 에 멤버필드에 잡혀있는 이름으로 해준다 -->
10. src.test.java 패키지 > MyBatisTest JUnit 생성
package com.smart.hrd;
import static org.junit.Assert.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import lombok.extern.log4j.Log4j;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class MyBatisTest {
@Autowired // 스프링 관리하는 빈(bean) 내에서 의존성(dependency)을 자동으로 주입(injection)해주는 기능
private SqlSessionFactory sqlFactory;
@Test
public void test() {
log.info(sqlFactory);
}
@Test // 테스트라는 어노테이션이 붙어있어야 호출된다.
public void testSession() {
try (SqlSession session = sqlFactory.openSession()) {
// io , database 객체, 빨간줄이 뜬다. 그러면 컴파일이 안되고 클래스 파일이 생성이 안되고, 실행이 안된다.
// 예외처리 종류 3가지 try catch, throws, throw
log.info(session);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run As 실행시 초록 불 떠야함
Mybatis 쓰는 방식이 3가지가 있다.
1. XML 기반 Mapper 사용 방식
2. 어노테이션 기반 Mapper 사용 방식
3. Mix 방식
3. Mapper interface 방식 - 댓글달기 할 때 수업할 예정
11. path 숨기기 > 서버 더블클릭 > Modules 클릭 > Edit...클릭
톰캣 서버 더블클릭
Moduls 클릭
Edit... 클릭
hrd 지우고 OK 클릭
Path 지워진 것 확인
톰캣 서버 실행버튼 클릭해주고
http://localhost:9000/
경로 들어가면 들어가면 잘 나옴
##
기존 -> /hrd/ 필요없어짐
경로숨기기
##
12. SampleController 클래스 생성
SampleController
package com.smart.hrd;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.log4j.Log4j;
@Controller // 컨트롤러가 찾아올 수 있게
@RequestMapping("/sample") //
// 또다른 방법 @RequestMapping("/sample/*")
@Log4j
public class SampleController {
@RequestMapping("") // 뒤에 경로를 안써주면 /sample 만 적어주면 실행됨
public void basic() {
log.info("basic1................................");
}
}
코드작성 후 톰캣서버 실행하고
http://localhost:9000/sample
접속하면
'수업 > 스프링' 카테고리의 다른 글
[Spring] 5일차 - json데이터 전송, 옛날json 데이터 전송, 파일전송, 에러발생시키기 (0) | 2023.04.13 |
---|---|
[Spring] 5일차 - domain 생성 및 SampleController 에서 사용 (0) | 2023.04.12 |
[Spring] 3일차 data base 연동, JUnit 연결 (0) | 2023.04.10 |
[Spring] 2일차 - 스프링 수업 시작! (0) | 2023.04.07 |
[Spring(스프링)] (0) | 2023.04.06 |