Spring/JPA

[JPA 활용1] 프로젝트 환경설정

Ynghan 2023. 3. 21. 22:30

프로젝트 환경설정

목차

  • 프로젝트 생성
  • 라이브러리 살펴보기
  • View 환경설정
  • H2 데이터베이스 설치
  • JPA와 DB 설정, 동작확인

프로젝트 생성

스프링 부트와 JPA를 가지고 프로젝트를 만듬.

※ 참고로 요즘은 JSP를 거의 안씀.

  • 스프링 부트 스타터(https://start.spring.io/)
  • 사용 가능 : web, thymeleaf, jpa, h2, lombok
    • groupId : jpabook
    • artifactId : jpashop

압축 해제하고 import

build.gradle로 실행

 

lombok은 plugin을 깔아야 한다.

File - Settings - Plugin - lombok 검색

Enable annotation processing 체크

 

라이브러리 살펴보기

./gradlew dependencies

spring boot starter는 logback을 기본적으로 사용한다.

핵심 라이브러리

  • 스프링 MVC
  • 스프링 ORM
  • JPA, 하이버네이트
  • 스프링 데이터 JPA

기타 라이브러리

  • H2 데이터베이스 클라이언트
  • 커넥션 풀 : 부트 기본은 HikariCP
  • WEB(thymeleaf)
  • 로깅 SLF4J & LogBack
  • 테스트

※ 스프링 데이터 JPA는 스프링과 JPA를 먼저 이해하고 사용해야 하는 응용기술이다.

View 환경 설정

thymeleaf 템플릿 엔진을 사용

※ 스프링 (부트) 공부할 때 GUIDES에 들어가서 Serving Web Content를 검색하여 따라해본다.

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");
        return "hello";
    }

 model이라는 객체에 데이터를 실어서 View에 넘길 수 있다.

정적 리소스는 static에 넣는다. 템플릿 엔진을 사용해야 할 경우는 templates에 넣는다.

수정사항이 많아 서버를 재실행하기 번거로운 경우

implementation 'org.springframework.boot:spring-boot-devtools'
  • build.gradle에 추가하기
  • Build - Recompile 'hello.html' 실행하면 자동 수정됨.

application.yml

spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/jpashop;MVCC=TRUE
    username: sa
    password:
    driver-class-name: org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        show_sql: true
        format_sql: true

SpringBoot - Learn - Reference Doc.

 

쿼리 파라미터 로그 남기기

외부 라이브러리 사용
: https://github.com/gavlyukovskiy/spring-boot-data-source-decorator

 

GitHub - gavlyukovskiy/spring-boot-data-source-decorator: Spring Boot integration with p6spy, datasource-proxy, flexy-pool and s

Spring Boot integration with p6spy, datasource-proxy, flexy-pool and spring-cloud-sleuth - GitHub - gavlyukovskiy/spring-boot-data-source-decorator: Spring Boot integration with p6spy, datasource-p...

github.com

※ 쿼리 파라미터를 로그로 남기는 외부 라이브러리는 시스템 자원을 사용하므로, 개발 단계에서는 편하게 사용해도 된다.
하지만 운영시스템에 적용하려면 꼭 성능테스트를 하고 사용하는 것이 좋다.