능글맞은 구렁이
spring-JPA 본문
JPA를 이용하여 DB연동 구현을 위한 준비작업 1. persistence.xml
1. META-INF=> persistence.xml: JAP 환경설정 파일 (반드시 존재해야한다.)
2. <persistence-unit name="JPAProject"></persistence-unit>
=> "JPAProject"는 DAO클래스에서 EntityManagerFactory 객체 생성시 필요한 이름
=> <persistence-unit>~~~</persistence-unit>은 데이터베이스마다 1개씩 존재해야한다.
3. <persistence-unit>~~~</persistence-unit> 내부
1) <class>~~</class>를 이용하여 Entity클래스를 등록해야한다.
2) <property>~~</property>를 이용하여 DB연동에 필요한 정보를 등록한다.
3) <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect"/>
: JPA는 해당 DBMS에 대한 테이블/쿼리등을 자동생성하기 때문에 hibernate-core~~.jar 내의
org.hibervate.dialect패키지에서 확인가능 (가장중요하다)
4. 옵션 속성 즉 선태사항에 대한 코드를 작성한다.
<persistence-unit name="JPAProject">
<class>com.jbr.biz.borad.Board</class>
<properties>
<!-- 필수 속성 -->
<property name="javax.persistence.jdbc.driver" value="DB드라이명"/>
<property name="javax.persistence.jdbc.user" value="계정"/>
<property name="javax.persistence.jdbc.password" value="비밀번호"/>
<property name="javax.persistence.jdbc.url" value="DB접속주소"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle12cDialect"/>
<!-- 옵션 속성 (선택사항)-->
<property name="hibernate.show_sql" value="true"/> <!-- 생성자 sql을 실행할때 생성자 sql부문을 콘솔창에 출력하겠다 ture 출력하지 않겠다. false -->
<property name="hibernate.format_sql" value="true"/><!-- 자바코드 입력하듯이 들여쓰기를이용하여 출력하겠다. -->
<property name="hibernate.use_sql_comments" value="false"/><!-- sql에 내부에 주석이 잇으면 주석을 포함하여 출력하겠다. ture 출력하지 않겠다.false -->
<property name="hibernate.id.new_generator_mappings" value="true"/><!-- 새로운 키 생성을 허용하겠다. -->
<property name="hibernate.hbm2ddl.auto" value="create"/><!--프로젝트 초기에 JPA테스트용ㅇ로 사용 -->
</properties>
</persistence-unit>
JPA를 이용하여 DB연동 구현을 위한 준비작업 2. Entity 클래스 작성
방법1. POJO형태로 작성가능 (persistence.xml에 등록해야함) 1) POJO스타일이란? public class Board{~~~} 방법2. JPA 플러그인 작성가능 (persistence.xml에 자동 등록됨) 1) JPA 플러그인을 이용한 형태란?publid class Board implementes Serializable{~~} ※참고 : Serializable의 역할: 자바에서 데이터를 외부에 저장할 때, 객체를 저장가능.객체 자체를 외부로 내보낼 경우에는 반드시 Serializable를 구현받아야 한다. 객체 내부의 멤버변수에 대한 데이터 형을 유지할 수 있다. |
1. 클래스 선언부 위에는 반드시 @Entity어노테이션이 반드시 존재해야한다.
: @Entity어노테이션이 붙은 클래스는 JPA의 persistence Context영역에서 관리한다.
2. 클래스 내부에서는 private 멤버변수가 선언되어 있어야 한다.
3. 기본 생성자도 명시, 그리고 private멤버변수에 대한 getter/setter도 필요하다.
(toString 재정의 메서드는 선택사항)
4. @Entity붙은 클래스는 반드시 @id 어노테이션이 붙는 멤버변수가 존재해야만 JPA가 처리할 수 있다.
(테이블 생성 및 시퀀스 생성 등의 DDL처리)
5. @Entity붙은 클래스의 멤버변수들에게는 그 외의 어노테이션을 이용하여 별도의 기능을 부여할 수 있다.
실제연동
1. EntityManegerFactory객체생성 : EntityManeger 객체를 생성하기위한 객체
-> Persistence.createEntityManagerFactory("persistence-unit의 name");
2. EntityManeger 객체생성 : DB관련 일을 처리하는 객체
-> EntityManegerFactory 객체.createEntityManeger ();
3. EntityTransaction 객체생성 : JPA는 반드시 transaction을 이용하여 처리해야 한다.
-> EntityManeger 객체.getTransaction();
4. 기본구조
try{
EntityTransaction 객체.begin(); //트랜잭션 시작
중간생략
EntityTransaction 객체.commit(); //실제적용
}catch(Exception e){
EntityTransaction 객체.rollback(); //.begin();~~예외발생 시점까지 처리내용을 원래대로 되돌리기
}finally {
em.close();
}
emf.close();
※Spring에서 사용하는 JPA 레퍼런스 URL
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.repositories
Spring Data JPA - Reference Documentation
Example 109. Using @Transactional at query methods @Transactional(readOnly = true) interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") void del
docs.spring.io
※JPA 자체 레퍼런스 URL
https://www.objectdb.com/api/java/jpa
JPA API Reference (JavaDoc) - Persistence, EntityManager, EntityTransaction, Query, etc.
This reference contains the API documentation (similar to JavaDoc) of the Java Persistence API (JPA) 2.0. The content is derived from the original JPA documentation (in the EclipseLink JPA 2 RI) with some additions and notes. The four most basic JPA types
www.objectdb.com
'Framework > Spring' 카테고리의 다른 글
Spring-JPA(환경설정) (0) | 2021.07.05 |
---|---|
Spring-JPA(개념) (0) | 2021.07.04 |
Lombok (0) | 2021.07.01 |
Spring - mybatis(Mapper XML) (0) | 2021.06.29 |
Spring-Mybatis (0) | 2021.06.29 |