우주먼지

💡 프로젝트 생성

  • https://start.spring.io/
  • Gradle 프로젝트
  • Spring Boot 버전은 3.0.0 이상으로 설정한다. (개인적으로 3.0이상 버전을 경험을 위함)
  • JDK 17
  • 라이브러리 : Web, Lombok, Thymeleaf, JPA, H2 Database
  • SSR (Server Side Rendering) 방식을 Default로 한다.

 

thymeleaf 공식 사이트: https://www.thymeleaf.org/

스프링 공식 튜토리얼: https://spring.io/guides/gs/serving-web-content/

스프링부트 메뉴얼: https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-template-engines

 

application.yml 설정

기본적인 JPA 스키마, 쿼리 설정과 H2 경로 등을 설정한다.

이후, H2 접속은 localhost:8080/h2로 접속하면 된다.

쿼리 파라미터 로깅 trace 옵션으로도 만족이 안되면 외부 라이브러리를 가져와서 쓰자.

implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.5.6'

쿼리 파라미터 로깅

  • Spring boot 2.x : org.hibernate.type: trace
  • Spring boot 3.x : org.hibernate.orm.jdbc.bind: trace

https://github.com/gavlyukovskiy/spring-boot-data-source-decorator

server:
# Log Encoding
  servlet:
    encoding:
      force-response: true
      charset: UTF-8


spring:
# JPA Settings
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
    properties:
      hibernate:
        format_sql: true # SQL Pretty Print

# H2 Settings
  h2:
    console:
      enabled: true
      path: /h2
  datasource:
    url: jdbc:h2:mem:shop
    driver-class-name: org.h2.Driver

# Logging Settings
logging:
  level:
    org.hibernate.sql: debug
    org.hibernate.orm.jdbc.bind: trace # 쿼리 파라미터 로깅

 

Spring Boot 3.0 이상 버전 P6Spy 적용

  • src/resources/META-INF/spring 밑에 파일 추가
    • 파일명 - org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.github.gavlyukovskiy.boot.jdbc.decorator.DataSourceDecoratorAutoConfigurati on
  • src/resources 밑에 파일 추가
    • 파일명 - spy.properties
appender=com.p6spy.engine.spy.appender.Slf4JLogger

💡 Template Engine

thymeleaf viewName 매핑

  • 컨트롤러에서 html 파일 명을 반환하면 html이 렌더링 된다.
  • resources/templates/ +{ViewName}+ .html
@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello");
        return "hello";
    }
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>

 

Static Html 사용

  • resoutces/static/index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

💡 기본 엔티티 생성 & 테스트

Entity

PK와 Name 필드 생성

@Entity @Getter @Setter
public class Member {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

 

Repository

멤버를 저장 & 조회하는 메서드 생성

@Repository
public class MemberRepository {

    @PersistenceContext
    private EntityManager em;

    public Long save(Member member) {
        em.persist(member);
        return member.getId();
    }

    public Member find(Long id) {
        return em.find(Member.class, id);
    }
}

 

Test

이번 강의는 JUnit4를 기준으로 하지만 개인적으로 JUnit5를 선호해서 JUnit5로 진행한다.

Test에서의 @Transactional 어노테이션은 테스트가 끝나면 데이터를 RollBack 한다.

Assertions 만으로 불안하면 @RollBack을 False로 주고 H2 DB에 데이터가 잘 들어가는지 보자.

@SpringBootTest
class MemberRepositoryTest {

    @Autowired
    MemberRepository memberRepository;

    @Test
    @DisplayName("Save 테스트")
    @Transactional
    public void testMember() {
        // Given
        Member member = new Member();
        member.setName("A");

        // When
        Long id = memberRepository.save(member);
        Member result = memberRepository.find(id);

        // Then
        Assertions.assertThat(result.getId()).isEqualTo(member.getId());
        Assertions.assertThat(result.getName()).isEqualTo(member.getName());
    }
}

'Inflearn 강의 > JPA 실전 활용' 카테고리의 다른 글

엔티티 개발  (0) 2023.03.23
도메인 분석 설계  (0) 2023.03.23
profile

우주먼지

@o귤o

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그