1. 프로젝트 생성
- 메이븐 설정
• groupId: jpa-basic
• artifactId: ex1-hello-jpa
• version: 1.0.0
라이브러리 추가 - pom.xml
자바 11
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>jpa-basic</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- JPA 하이버네이트 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.10.Final</version>
</dependency>
<!-- H2 데이터베이스 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
</dependencies>
</project>
JPA 설정하기 - persistence.xml
- JPA 설정 파일
• /META-INF/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="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"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!-- 옵션 -->
<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 구동 방식
- persistence.xml파일을 조회하여 Persistence 생성
- Persistence가 java 파일이 돌아갈때 EntityManagerFactory를 하나 생성
- EntityManagerFactory에서 트랜잭션이 필요할 때마다 EntityManager를 생성하여 트랜잭션에 책임 위임
주의
- 엔티티 매니저 팩토리는 하나만 생성해서 애플리케이션 전체에 서 공유
• 엔티티 매니저는 쓰레드간에 공유X (사용하고 버려야 한다).
• JPA의 모든 데이터 변경은 트랜잭션 안에서 실행
JPQL
- 간단한 조회가 아닌 ID가 2이상인 회원 조회하고 싶을때 사용
- SQL과 문법 유사
- JPQL은 엔티티 객체를 대상으로 쿼리
- SQL은 데이터베이스 테이블을 대상으로 쿼리
'JPA > JPA Basic' 카테고리의 다른 글
[JPA] 5. 다양한 연관관계 매핑 (0) | 2023.01.29 |
---|---|
[JPA] 참고. @JoinColumn (0) | 2023.01.29 |
[JPA] 참고. Entity, DAO, DTO, VO (0) | 2023.01.27 |
[JPA] 에러. SQL Error 23505 (0) | 2023.01.27 |
[JPA] 4. 연관관계 매핑 기초 (0) | 2023.01.27 |
[JPA] 3. 엔티티 매핑 (0) | 2023.01.26 |
[JPA] 2. 영속성관리 (0) | 2023.01.25 |
[JPA] 0. JPA 소개 (0) | 2023.01.25 |