티스토리 뷰

 

0. 프로젝트 구조

 

1. build.gradle > dependencies

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

// jpa binding parameter log 확인
implementation("com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.7.1")

 

2. application.yml

server:
  port: 8088

spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/nutrient
    username: sa
    password:
    driver-class-name: org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        format_sql: true # sql 로그에서 확인
        # show_sql: true

logging.level:
  org.hibernate.SQL: debug
#  org.hibernate.type: trace # binding parameter 확인 (p6spy 로 대체)

 

3. entity 생성

package mandykr.nutrient.entity;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Supplements {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
}

 

4. repository 생성

package mandykr.nutrient.repository;

import mandykr.nutrient.entity.Supplements;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Repository
public class SupplementsRepository {
    @PersistenceContext
    private EntityManager em;

    public Long save(Supplements supplements) {
        em.persist(supplements);
        return supplements.getId();
    }

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

 

5. 테스트

package mandykr.nutrient;

import mandykr.nutrient.entity.Supplements;
import mandykr.nutrient.repository.SupplementsRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
@Transactional
class SupplementsRepositoryTests {
	@Autowired
	SupplementsRepository supplementsRepository;

	@Test
	@Commit
	void save() {
		Supplements supplements = new Supplements();
		supplements.setName("빌베리 플러스");

		Long supplementsId = supplementsRepository.save(supplements);
		Supplements findSupplements = supplementsRepository.find(supplementsId);

		assertThat(supplementsId).isEqualTo(findSupplements.getId());

		System.out.println("supplementsId = " + supplementsId);
		System.out.println("findSupplements id = " + findSupplements.getId());
	}

}

 

6. 로그 및 DB 확인

1) 로그

 - application.yml 의 org.hibernate.type: trace 설정일 때

 

 - build.gradle 의 p6spy 설정일 때

2) DB

 

 

 

 

출처

https://www.inflearn.com/course/스프링부트-JPA-활용-1 실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발(김영한)

728x90