상세 컨텐츠

본문 제목

리포지터리로 데이터베이스 관리하기 (2)

스프링부트(Spring Boot)

by 230719 2025. 2. 2. 23:54

본문

앞서 작성한 SbbApplicationTests 클래스를 실행하자. 

파일을 우클릭 한 후, Run As -> JUnit Test 를 선택하면 된다.

 

당황스러운 WARNING 메시지

실행은 잘 된 것 같은데 에러 메시지가 뜬 것 같다.
Mockito is currently ~~ 라는 메시지는 Mockito 가 인라인 모킹을 위해 자체적으로 Java Agent를 로드했는데, JDK 21 이후로는 기본적으로 차단될 예정이라는 경고라고 한다.
build.gradle의 dependencies에서 아래 코드를 추가하면 해결이 가능하다고 한다.

testImplementation 'org.mockito:mockito-inline'

음... 추가 한 후 다시 테스트코드를 실행해보았지만, 오류가 그대로 남아있다.

테스트 실행 자체는 정상적으로 수행되고, 경고메시지지만 지금 당장 큰 문제는 아닌 것 같으므로 일단 넘어가려고 한다.

테스트 코드 실행 JUnit 화면

이러한 JUnit 화면이 나타나고 초록색 바가 표시된다.

 

실제 데이터베이스에 값이 잘 들어갔는지 확인해 보기 위해 다시 로컬 서버를 시작하고 H2 콘솔에 접속하여 쿼리문을 실행하자.

SELECT * FROM QUESTION

먼저 로컬 서버를 재시작하고,

아래의 URL로 접속하여 H@ 콘솔에 접속한다.

http://localhost:8080/h2-console

 

위의 SQL문을 작성한 후, Run 또는 실행을 클릭한다.

Run을 클릭하면,

잘 표시되는 걸 확인할 수 있다.


질문 데이터 조회하기

리포지터리가 제공하는 메서드들을 하나씩 살펴보자.

 

findAll 메서드

SbbApplicationTests.java 파일에서 작성한 테스트 코드를 다음과 같이 수정해 보자.

package com.mysite.sbb;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class SbbApplicationTests {

    @Autowired
    private QuestionRepository questionRepository;

    @Test
    void testJpa() {
        List<Question> all = this.questionRepository.findAll();
        assertEquals(2, all.size());

        Question q = all.get(0);
        assertEquals("sbb가 무엇인가요?", q.getSubject());
    }
}

 

this.questionRepository.findAll(); - question 테이블에 저장된 모든 데이터를 조회하기 위해서 questionRepository의 findAll 메서드를 사용했다. ( = SELECT * FROM QUESTION)

 

앞서 2개의 질문 데이터를 저장했기 때문에 데이터사이즈는 2가 되어야 한다. 데이터사이즈가 2인지 확인하기 위해 JUnit의 assertEquals 메서드를 사용하는데, 이 메서드는 테스트에서 예상한 결과와 실제 결과가 동일한지를 확인하는 목적으로 사용한다. 
JPA 또는 데이터베이스에서 데이터를 올바르게 가져오는지를 확인하려는 것이다. assertEquals(기댓값, 실젯값) 와 같이 작성하고 기댓값과 실젯값이 동일한지를 조사한다. 
로컬서버를 중지하고 다시한번 Run As -> JUnit Test를 실행해보자. 테스트가 성공했다고 표시되었다. 

 

findById 메서드

이번에는 엔터티의 기본키인 id의 값을 활용해 데이터를 조회해보자. 

테스트 코드를 다음과 같이 수정하자. 

package com.mysite.sbb;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class SbbApplicationTests {

    @Autowired
    private QuestionRepository questionRepository;

    @Test
    void testJpa() {
        Optional<Question> oq = this.questionRepository.findById(1);
        if(oq.isPresent()) {
            Question q = oq.get();
            assertEquals("sbb가 무엇인가요?", q.getSubject());
        }
    }
}

id 값으로 데이터를 조회하기 위해서는 리포지터리의 findById 메서드를 사용해야한다. 여기서는 questionRepository를 사용하여 데이터베이스에서 id가 1인 질문을 조회한다.

this.quesitonRepository.findById(1);

이때 findById의 리턴타입은 Question이 아닌 Optional이다. 호출한 값이 존재할 수도 있고, 존재하지 않을 수도 있어서 리턴 타입으로 Optional이 사용된 것이다. 

이것도 테스트를 통과하게 된다.

 

findBySubject 메서드

리포지터리는 findBySubject 메서드를 기본적으로 제공하지는 않는다. 그래서 다음의 메서드를 사용하려면 QuestionRepository 인터페이스를 변경해야한다. src/main/java 디렉터리의 com.mysite.sbb 패키지의 QuestionRepository.java를 수정하자. 

package com.mysite.sbb;

import org.springframework.data.jpa.repository.JpaRepository;

public interface QuestionRepository extends JpaRepository<Question, Integer> {
    Question findBySubject(String subject);
}

QuestionRepository.java

 

다시 src/test/java 디렉터리의 com.mysite.sbb 패키지의 SbbApplicationTests.java를 수정해 subject 값으로 테이블에 저장된 데이터를 조회하자. 

package com.mysite.sbb;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class SbbApplicationTests {

    @Autowired
    private QuestionRepository questionRepository;

    @Test
    void testJpa() {
        Question q = this.questionRepository.findBySubject("sbb가 무엇인가요?");
        assertEquals(1, q.getId());
    }
}

SbbApplicationTests.java

 

findBySubject 메서드를 호출할 때 실제 데이터베이스에서는 어떤 쿼리문이 실행되는 지 살펴보자. 실행되는 쿼리문은 콘솔로그에서 확인할 수 있다. 다음과 같이 src/main/resources 디렉터리의  application.properties 파일을 수정해보자. 

# DATABASE 
spring.h2.console.enabled=true 
spring.h2.console.path=/h2-console 
spring.datasource.url=jdbc:h2:~/local 
spring.datasource.driverClassName=org.h2.Driver 
spring.datasource.username=sa 
spring.datasource.password= 

# JPA 
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect 
spring.jpa.hibernate.ddl-auto=update 
spring.jpa.properties.hibernate.format_sql=true 
spring.jpa.properties.hibernate.show_sql=true

그리고 테스트 코드를 실행해보자. 

 

 

And findBySubjectAndContent(String subject, String content) Subject, Content 열과 일치하는 데이터를 조회
Or findBySubjectOrContent(String subject, String content) Subject열 또는 Content 열과 일치하는 데이터를 조회
Between findByCreateDateBetween(LocalDateTime fromDate, LocalDateTime toDate) CreateDate 열의 데이터 중 정해진 범위 내에 있는 데이터를 조회
LessThan findByIdLessThan(Integer id) Id 열에서 조건보다 작은 데이터를 조회
GreaterThanEqual findByIdGreaterThanEqual(Integer id) Id 열에서 조건보다 크거나 같은 데이터를 조회
Like findBySubjectLike(String subject) Subject 열에서 문자열 ‘subject’와 같은 문자열을 포함한 데이터를 조회
In findBySubjectIn(String[] subjects) Subject 열의 데이터가 주어진 배열에 포함되는 데이터만 조회
OrderBy findBySubjectOrderByCreateDateAsc(String subject) Subject 열 중 조건에 일치하는 데이터를 조회하여 CreateDate 열을 오름차순으로 정렬하여 반환

 

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation

 

Spring Data JPA :: Spring Data JPA

Oliver Gierke, Thomas Darimont, Christoph Strobl, Mark Paluch, Jay Bryant, Greg Turnquist Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that

docs.spring.io

공식 문서도 참고하자.

 


질문 데이터 수정하기

질문 엔터티의 데이터를 수정하는 테스트 코드를 작성해보자.

package com.mysite.sbb;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class SbbApplicationTests {

    @Autowired
    private QuestionRepository questionRepository;

    @Test
    void testJpa() {
        Optional<Question> oq = this.questionRepository.findById(1);
        assertTrue(oq.isPresent());
        Question q = oq.get();
        q.setSubject("수정된 제목");
        this.questionRepository.save(q);
    }
}

'스프링부트(Spring Boot)' 카테고리의 다른 글

데이터베이스 구축  (0) 2025.04.03
리포지터리로 데이터베이스 관리하기  (1) 2025.01.28
테이블 매핑하기  (0) 2025.01.27
JPA 데이터베이스 사용하기  (1) 2025.01.27
웹 만들어보기  (0) 2025.01.20

관련글 더보기