
JPA는 ORM 기술 중 하나.
ORM은 Object-relational-mapping(객체 관계 매핑)의 약자. 말그대로 객체를 이용하여 매핑하는 것.
애플리케이션과 데이터베이스 사이에서 객체 지향 페러다임을 이용 데이터베이스를 다룰 수 있는 프레임워크.
따라서, JPA는 관계형 데이터베이스(RDBMS) 와 객체지향형 프로그래밍(OOP) 의 간격을 좁히기 위해 나온 자바 진영의 ORM 표준 기준.
JPA 특징
- 애노테이션을 이용한 매핑 설정
- XML파일을 이용한 매핑 설정 가능
- String, int, LocalDate 등 기본적인 타입에 대한 매핑 지원
- 커스텀 타입 변환기 지원
- 내가 만든 Money 타입을 DB칼럼에 매핑 가능
- 밸류 타입 매피 지원
(참고 : https://velog.io/@qf9ar8nv/spring-jpa)
의존 추가 후, 아래의 persistence.xml 파일 작성
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<!-- 영속 단위(영속성 관리 단위) 이름 -->
<persistence-unit name="jpabook">
<properties>
<!-- DB 연결 설정 (필수 속성) -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/test"/>
<!-- Hibernate DB 종류 설정(옵션) -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
<!-- 커넥션풀 설정 -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
<!--<property name="hibernate.hbm2ddl.auto" value="create" />-->
</properties>
</persistence-unit>
</persistence>
JPA: 기술 명세 (정의)
Hibernate: JPA 기술 구현체
@Entity // DB 테이블과 매핑 대상
@Table(name="user") // USER 테이블과 매핑
public class User {
@Id // 식별자에 대응
private String email; // email 칼럼과 매핑
private String name; // name 칼럼과 매핑
@Column(name = "create_date") // create_date 칼럼과 매핑
private LocalDateTime createDate;
protected User(){}
public User(String email, String name, LocalDateTime createDate){
this.email = email;
this.name = name;
this.createDate = createDate;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public LocalDateTime getCreateDate() {
return createDate;
}
public void changeName(String newName){
this.name = newName;
}
}
@Id : Table은 기본적으로 유일한 값을 가짐(PK[primary Key]). PK를 지정할때 사용.Link: github
Link: github
Link: github
추가 설명 (추후에 자세하게 배움!)
EntityManagerFactory: Enitity 생성EntityManage: DB와의 연동 처리.persist(): 파라미터로 전달한 객체를 DB에 저장