[REST API] JPA와 Hibernate를 이용해 REST API에 H2 연결하기 개요 & User Entity 만들고, test data 생성하기

민지·2024년 3월 18일
0

REST API - Spring Boot

목록 보기
23/27

JPA와 Hibernate를 이용해 REST API를 H2에 연결하기 - 개요

이제 SpringBoot 기본구조 및 기본기능, 고급기능까지 살펴봤다. 그럼 이제 데이터베이스와 스프링부트를 서로 연결하는 작업만 남았다!
또한 앞서 스프링부트로 todo-list를 만들 때, JPA와 Hibernate로 H2와 연결하는 방법도 정리해두었었다.

이번 포스팅에서는, JPA와 Hibernate를 이용해 REST API를 데이터베이스에 연결하는 방법을 중점적으로 살펴볼 것!

  • 인메모리 데이터베이스 H2로 배운 뒤, MySQL을 적용할 것
  • 기존의 UserResource 컨트롤러를 update할 것
    기존 → UserResource컨트롤러가 정적 리소스와 그 기능을 담은 UserDaoService를 사용했다면,
    update → UserResource 컨트롤러가 UserDaoService 대신 JpaRepository를 상속한 UserRepository를 만들 것

application.properties

H2-console 사용을 위해 다음을 추가할 것

spring.h2.console.enabled=true

User Entity 만들고, test data 생성하기

1. User.java -> @Entity 추가, @Id, @GeneratedValue

@Entity(name = "user_details")
public class User {

	protected User() {

	}

	@Id
	@GeneratedValue // id값이 생성되어야 하니
	private Integer id;

	@Size(min = 2, message = "Name should have atleast 2 characters")
	//@JsonProperty("customized_userName")
	private String name;

	@Past(message = "Birth Date should be in the past")
	//@JsonProperty("customized_birthDate")
	private LocalDate birthDate;
	.
	.
	// same code
}

2. application.properties Modified → 정적 h2 url 사용

spring.datasource.url=jdbc:h2:mem:testdb 
spring.jpa.defer-datasource-initialization=true

spring.datasource.url=jdbc:h2:mem:testdb → 정적 h2 url 사용

spring.jpa.defer-datasource-initialization=true → 이거 추가안하면, 데이터베이스 테이블이 생성되기도 전에, sql문이 먼저 실행되 에러가 발생한다. (todolist, 23번째글, @Entity에 나옴) 해당 에러를 수정하기 위해 덧붙인 설정!

URLS

src/main/resources/data.sql New

몇개의 sql문을 실행시켜, h2-console에 데이터값을 넣어보자

insert into user_details(id,birth_date,name)
values(10001, current_date(), 'minjiki2_sql_1');

insert into user_details(id,birth_date,name)
values(10002, current_date(), 'minjiki2_sql_2');

insert into user_details(id,birth_date,name)
values(10003, current_date(), 'minjiki2_sql_3');

실행결과,



참고 및 출처

이 시리즈는 Udemy 강의의 내용을 정리한 것입니다.
https://www.udemy.com/course/spring-boot-and-spring-framework-korean/

profile
배운 내용을 바로바로 기록하자!

0개의 댓글