JPA란
데이터 생성, 저장, 조회, 수정
ORM을 이용하면 데이터베이스 종류에 상관 없이 일관된 코드를 유지할 수 있어서 프로그램을 유지·보수하기가 편리하다. 또한 내부에서 안전한 SQL 쿼리를 자동으로 생성해 주므로 개발자가 달라도 통일된 쿼리를 작성할 수 있고 오류 발생률도 줄일 수 있다.
데이터베이스를 사용하려면 SQL 쿼리(query)라는 구조화된 질의를 작성하고 실행하는 등의 복잡한 과정이 필요하다.
Primary Key
Hibernate
H2 데이터베이스
(... 생략 ...)
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
}
(... 생략 ...)
build.gradle파일 dependecies에
runtimeOnly 'com.h2database:h2' 추가
# 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=
application.properties 파일 수정
spring.h2.console.enabled -> H2 콘솔의 접속을 허용할지의 여부이다. true로 설정한다.
spring.h2.console.path -> 콘솔 접속을 위한 URL 경로이다.
spring.datasource.url -> 데이터베이스 접속을 위한 경로이다.
spring.datasource.driverClassName -> 데이터베이스 접속시 사용하는 드라이버이다.
spring.datasource.username -> 데이터베이스의 사용자명이다. (사용자명은 기본 값인 sa로 설정한다.)
spring.datasource.password -> 데이터베이스의 패스워드이다. 로컬 개발 용도로만 사용하기 때문에 패스워드를 설정하지 않았다.
build.gradle 파일 수정
(... 생략 ...)
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
}
(... 생략 ...)
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
Controller -> java 로직 수행
Entity -> 테이블 정보 설정
Repository -> 쿼리 정보 설정