* 하이버네이트 버전설정, db 설정
<?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>jpa-basic</groupId>
<artifactId>ex1-hello-jpa</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- JPA 하이버네이트 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.2.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- H2 데이터베이스 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.224</version>
</dependency>
<!-- logback -->
<!--
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.14</version>
</dependency>
-->
</dependencies>
</project>
<?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"/> //db 뭐쓸건지
<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"/> //쿼리 sql 보여줄건지
<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>
* h2 database not found 해결
해결방법
- C:\Users\사용자명 위치에서 txt 파일 새로 만들기 - 다른이름으로 저장하기
- 파일 이름 : test.mv.db
- 파일 형식 : 모든 파일(*.*)
- 저장하면 db 생성 완료
출처: https://nyximos.tistory.com/73 [nyximos.log:티스토리]
* javax vs jakarta
https://www.samsungsds.com/kr/insights/java_jakarta.html
package hellojpa;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Member {
@Id
private Long id;
private String name;
//Getter, Setter …
}
* 쿼리날려보기
public class JpaMain {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello"); //프로젝트당 1개
EntityManager em = emf.createEntityManager(); //em은 트랜잭션(작업)당 1개
Member member = new Member();
member.setId(1L);
member.setName("Jack");
em.persist(member);
em.close();
emf.close();
}
}
* 원인 : data를 변경하는 모든작업은 트랜잭션 안에서 해야함
* 해결
package hellojpa;
import jakarta.persistence.*;
public class JpaMain {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello"); //프로젝트당 1개
EntityManager em = emf.createEntityManager(); //em은 트랜잭션(작업)당 1개
EntityTransaction tx = em.getTransaction(); //트랜잭션열기
tx.begin();
Member member = new Member();
member.setId(1L);
member.setName("Jack");
em.persist(member);
tx.commit(); //커밋
em.close();
emf.close();
}
}
* 문제 : em.persist등 위에서문제생기면, em.close등 다음코드가 실행이안됨
* 해결 : try, catch
package hellojpa;
import jakarta.persistence.*;
public class JpaMain {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello"); //프로젝트당 1개
EntityManager em = emf.createEntityManager(); //em은 트랜잭션(작업)당 1개
EntityTransaction tx = em.getTransaction(); //트랜잭션열기
tx.begin();
try{
Member member = new Member();
member.setId(2L);
member.setName("Kang");
em.persist(member);
tx.commit(); //커밋
}
catch(Exception e){
tx.rollback(); //예외시 롤백
}
finally {
em.close();
}
emf.close();
}
}
* if exist member, auto drop 해결 // 삽입시 db가 초기화되는 문제 해결
pom.xml에서 해당부분 주석하면 된다.
<!-- <property name="hibernate.hbm2ddl.auto" value="create" />-->
* 회원 조회
* !!수정!!
* persist를 안해도 되는이유 : jpa를 통해서 entity를가져옴 -> jpa가 관리하는 entity가 됨 -> jpa가 커밋시점에 객체가 변경됬는지 체크 -> 바꿧으면 update 쿼리를 날림
* JPQL : 객체지향 쿼리
방언에맞춰서 db에 맞게 변형해줌
특정 db에 대한 의존성을 줄임.
* 무슨이득이있지? : 페이징