Spring boot DB 조회 - Spring boot DB johoe

https://100winone.tistory.com/5

[SpringBoot] RestAPI 이용해서 "HelloWorld 띄우기"

RestAPI 를 이용해 페이지에 "Hello World!" 를 띄워보겠다. 그러기 위해서는 Spring Boot Web Starter를 Gradle에 추가해줘야 하는데 밑에 링크 참조~! https://100winone.tistory.com/4?category=814160 [Spring..

100winone.tistory.com

Spring boot DB 조회 - Spring boot DB johoe

이전 게시물에선 Controller 단에서 "HelloWorld"만 띄워봤다.

이번 게시물에서는 Controller->Service->ServiceImpl->Mapper->xml 순서로 DB에 접근하여 값을 Select을 해보겠다!

Spring boot DB 조회 - Spring boot DB johoe

기본적인 구성은 이렇게 된다!

Spring boot DB 조회 - Spring boot DB johoe

일단 DB에 접근하기 위해 gradle에 mybatis-spring-boot-starter와 spring-boot-starter-jdbc 의존성 주입을 해준다.

가장 밑에 'compile fileTree(dir: 'libs', include: ['*.jar'])'를 추가한 이유는

Spring boot DB 조회 - Spring boot DB johoe

libs 폴더를 만들고 필요한 jar 파일을 의존성 주입해 사용하기 위해서이다!!

이제 본인에 접근할 DB에 대한 설정을 src/main/resources 아래에 application.properties에 넣어준다.

Spring boot DB 조회 - Spring boot DB johoe
Spring boot DB 조회 - Spring boot DB johoe

이런식으로 넣어주면된다!

Spring boot DB 조회 - Spring boot DB johoe

mybatis를 쓰기 위해 config아래에 MybatisSimpleConfig 클래스를 추가해준다.

후에 dynamic 쿼리를 사용할 때 필요하기 때문에 미리 추가해준다!

basePackage = ""에는 본인의 mapper 패키지 경로를 넣어주면 된다.

Controller

Spring boot DB 조회 - Spring boot DB johoe

Service단에 @Autowired 어노테이션을 사용해 접근해준다!!

Service

Spring boot DB 조회 - Spring boot DB johoe

Service단은 interface로 따로 구현하는 로직은 없고 getData()를 선언만 해준다.

구현은 ServiceImpl단에서!

ServiceImpl

Spring boot DB 조회 - Spring boot DB johoe

Service 단을 구현하기 위해 RestService를 implements 해주어야한다!!

@Autowired 어노테이션을 통해 Mapper에 접근하고 Mapper의 getData()값을 리턴받는다.

Mapper

Spring boot DB 조회 - Spring boot DB johoe

Mapper도 마찬가지로 interface이기때문에 따로 구현을 하진 않는다.

@Mapper 어노테이션을 정의해주고 SqlMapper.xml에서 쿼리를 사용해 DB에 접근할 것이다.

SqlMapper.xml

Spring boot DB 조회 - Spring boot DB johoe

xml 파일은 원하는 패키지 위에 커서를 두고 마우스 우클릭을 후에 New->mapper로 만들면 된다.

Spring boot DB 조회 - Spring boot DB johoe

namespace에는 mapper 클래스의 모든 경로를 적어주면 된다. 

select id=""에는 반환 받을 메소드 명을 적어주고, resultType에는 반환형을 적어준다.

그 안에 쿼리를 적어주면 끝!!

<결과화면>

Spring boot DB 조회 - Spring boot DB johoe