[JPA] 기초와 매핑

JPA 어노테이션
@Entity : JPA가 관리할 객체, create table로 생성한 테이블이랑 동일하다고 볼 수 있다.
@Id : DB의 PK와 매핑할 필드, id멤버변수를 프라이머리 키로 지정한 것과 동일하다고 볼 수 있다.
@Entity
public class Member {
@Id
private Long id;
private String name;
}
create table Member (
id bigint not null,
name varchar(255),
primary key(id)
);
JPA는 persistence.xml을 사용해서 필요한 설정 정보를 관리한다.
persistence.xml
JPA 설정 파일
/META-INF/persistence.xml에 위치
javax.persistence로 시작: JPA 표준 속성
hibernate로 시작: 하이버네이트 전용 속성
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="hello">
<properties>
<!-- 필수 속성 -->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/>
<!-- 데이터베이스 방언 DB교체시 손쉽게 변경할 수 있다.-->
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!-- 옵션 -->
<!-- 콘솔에 하이버네이트가 실행하는 SQL문 출력 -->
<property name="hibernate.show_sql" value="true"/>
<!-- SQL 출력 시 보기 쉽게 정렬 -->
<property name="hibernate.format_sql" value="true"/>
<!-- 쿼리 출력 시 주석(comments)도 함께 출력 -->
<property name="hibernate.use_sql_comments" value="true"/>
<!-- JPA 표준에 맞춘 새로운 키 생성 전략 사용 -->
<property name="hibernate.id.new_generator_mappings" value="true"/>
<!-- 애플리케이션 실행 시점에 데이터베이스 테이블 자동 생성 -->
<!-- <property name="hibernate.hbm2ddl.auto" value="create"/> -->
<!-- 이름 매핑 전략 설정 - 자바의 카멜 표기법을 테이블의 언더스코어 표기법으로 매핑
ex) lastModifiedDate -> last_modified_date -->
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
</properties>
</persistence-unit>
</persistence>
xmlns에 네임 스페이스, version에 사용할 JPA 버전을 지정한다.
<persistence-unit>의 name에 unit의 고유한 이름을 설정한다. 일반적으로 연결할 데이터베이스당 하나의 고유한 persistence unit을 등록한다.
여기서는 hello를 부여한다. persistence-unit name값이 중복되지만 않으면 아무이름값을 넣어도 상관없다.
그리고 <properties> 아래에 JPA 표준 속성과 하이버네이트 속성을 설정한다.
Database 방언(Dialect)
방언이란 서로 다른 Database간의 데이터 타입이나 페이징 처리등 SQL문법 차이를 말하며 JPA 구현체들은 이를 보정해 주기 위해 Dialect Class를 제공한다 이를 통해서 Database가 변경되어도 Dialect Class교체 만으로 코드 변경없이 문제를 해결 할 수 있게 된다.
Hibernate 의 Dialect 리스트는 아래 와 같다.
Name | 설명 |
Cache71Dialect | Caché 2007.1 dialect. |
DataDirectOracle9Dialect | |
DB2390Dialect | An SQL dialect for DB2/390. |
DB2400Dialect | An SQL dialect for DB2/400. |
DB2Dialect | An SQL dialect for DB2. |
DerbyDialect | Hibernate Dialect for Cloudscape 10 - aka Derby. |
Dialect | Represents a dialect of SQL implemented by a particular RDBMS. |
FirebirdDialect | An SQL dialect for Firebird. |
FrontBaseDialect | An SQL Dialect for Frontbase. |
H2Dialect | A dialect compatible with the H2 database. |
HSQLDialect | An SQL dialect compatible with HSQLDB (HyperSQL). HSQLDialect.ReadUncommittedLockingStrategy |
InformixDialect | Informix dialect. Seems to work with Informix Dynamic Server Version 7.31.UD3, Informix JDBC driver version 2.21JC3. |
Ingres10Dialect | A SQL dialect for Ingres 10 and later versions. |
Ingres9Dialect | A SQL dialect for Ingres 9.3 and later versions. |
IngresDialect | An SQL dialect for Ingres 9.2. |
InterbaseDialect | An SQL dialect for Interbase. |
JDataStoreDialect | A Dialect for JDataStore. |
MckoiDialect | An SQL dialect compatible with McKoi SQL. |
MimerSQLDialect | An Hibernate 3 SQL dialect for Mimer SQL. |
MySQL5Dialect | An SQL dialect for MySQL 5.x specific features. |
MySQL5InnoDBDialect MySQLDialect | An SQL dialect for MySQL (prior to 5.x). |
MySQLInnoDBDialect | |
MySQLMyISAMDialect | |
Oracle10gDialect | A dialect specifically for use with Oracle 10g. |
Oracle8iDialect | A dialect for Oracle 8i. |
Oracle9Dialect | Deprecated. Use either Oracle9iDialect or Oracle10gDialect instead |
Oracle9iDialect | A dialect for Oracle 9i databases. |
OracleDialect | Deprecated. Use Oracle8iDialect instead. |
PointbaseDialect | A Dialect for Pointbase. |
PostgresPlusDialect | An SQL dialect for Postgres Plus |
PostgreSQLDialect | An SQL dialect for Postgres For discussion of BLOB “support” in postrges, as of 8.4, have a peek at http://jdbc.postgresql.org/documentation/84/binary-data.html. |
ProgressDialect | An SQL dialect compatible with Progress 9.1C Connection Parameters required: hibernate.dialect org.hibernate.sql.ProgressDialect hibernate.driver com.progress.sql.jdbc.JdbcProgressDriver hibernate.url jdbc:JdbcProgress:T:host:port:dbname;WorkArounds=536870912 hibernate.username username hibernate.password password The WorkArounds parameter in the URL is required to avoid an error in the Progress 9.1C JDBC driver related to PreparedStatements. |
RDMSOS2200Dialect | This is the Hibernate dialect for the Unisys 2200 Relational Database (RDMS). |
ResultColumnReferenceStrategy | Defines how we need to reference columns in the group-by, having, and order-by clauses. |
SAPDBDialect | An SQL dialect compatible with SAP DB. |
SQLServer2008Dialect | A dialect for Microsoft SQL Server 2008 with JDBC Driver 3.0 and above |
SQLServerDialect | A dialect for Microsoft SQL Server 2000 and 2005 |
Sybase11Dialect | A SQL dialect suitable for use with Sybase 11.9.2 (specifically: avoids ANSI JOIN syntax) |
SybaseAnywhereDialect | SQL Dialect for Sybase Anywhere extending Sybase (Enterprise) Dialect (Tested on ASA 8.x) |
SybaseASE15Dialect | An SQL dialect targetting Sybase Adaptive Server Enterprise (ASE) 15 and higher. |
SybaseDialect | Deprecated. use AbstractTransactSQLDialect, SybaseASE15Dialect or SQLServerDialect instead depending on need. |
TeradataDialect | A dialect for the Teradata database created by MCR as part of the dialect certification process. |
TimesTenDialect | A SQL dialect for TimesTen 5.1. |
hibernate.hbm2ddl.auto 옵션 설명
옵션 | 설명 |
create | DROP + CREATE 기존 테이블을 삭제하고 새로 생성한다. |
create-drop | DROP + CREATE + DROP create 속성에 추가로 애플리케이션을 종료할 때 생성한 DDL을 제거한다. |
update | 데이터베이스 테이블과 엔티티 매핑정보를 비교해서 변경 사항만 수정한다. |
validate | 데이터베이스 테이블과 엔티티 매핑정보를 비교해서 차이가 있으면 경고를 남기고 애플리케이션을 실행하지 않는다. 이 옵션은 DDL을 수정하지 않는다. |
none | 스키마 자동 생성 기능을 사용하지 않는다. hibernate.hbm2ddl.auto 속성을 삭제한 것과 동일하다. |
운영 장비에는 절대 create, create-drop, update 사용하면 안된다.
개발 초기 단계는 create 또는 update
테스트 서버는 update 또는 validate
운영 서버는 validate 또는 none
Entity Class(엔티티 클래스) 설정
JPA 구현체들은 보통 엔티티 클래스를 자동으로 인식하지만 환경에 따라 인식하지 못할 때도 있다. 그때는 <class>에 엔티티 클래스를 설정해준다.
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="hello">
<class>com.dev.test.Member</class>
<properties>
<!-- 필수 속성 -->