jpa 개요

HYK·2021년 4월 17일
0

jpa

목록 보기
1/1

참고 : https://www.inflearn.com/course/ORM-JPA-Basic#

ORM 이란?

orm(Object-relation mapping)

  • orm은 기존의 데이터 베이스에 종속되어 설계하지 않도록 객체는 객체대로 설계하고 데이터베이스는 데이터베이스 대로 설계할 수 있도록 도와준다.
  • 즉 ORM 프레임워크가 데이터 베이스와 객체를 중간에서 매핑해준다.

JPA

JPA(java Persisten API)

  • 자바에서 사용되는 ORM 기술표준의 인터페이스.
  • 이를 구현한 프레임워크 중 하나가 Hibernate이다.

JPA 장점과 사용이유


1. 생산성이 높아진다.

  • 일반적인 프로젝트에서는 직접 작성해야하는 CRUD에 함수가 JPA는 이미 만들어져 있기 때문에 가져다 쓰기만 하면 된다.
  • 즉 직접 sql 문을 작성할 필요가 없다.

2. 유지 보수가 좋다

  • 기존의 프로젝트에서는 DB의 종류를 바꾸거나 칼럼을 수정할 때 모든 sql 문들을 하나씩 수정해야 하지만 JPA를 사용하면 DB를 바꿀 때는 방언 설정 하나만 바꿔주면 되고 칼럼과 같은 정보가 바뀌어도 엔티티만 수정하면 JPA가 알아서 처리해 준다.

3. 데이터베이스에 중점적 개발이 아닌 객체지향적으로 개발을 할 수 있다.

  • 예를 들어 Member Entity와 Team Entity를 설계할 때 데이터 베이스에서의 설계가 Member Table에 Team_id라는 Fk가 있다고 가정하면 기존에는 객체를 보통 아래와 같이 설계한다.

  1. 첫번째
class Member1{
	private Long id;
    	private Long teamid;
}
class Team1{
	private Long id;
}
  1. 두번째
class Member1{
	private Long id;
    	private Long teamid;
}
class Team1{
	private Long id;
}

여기서 첫 번째처럼 짜기에는 객체지향적이지 않게 설계가 됐고 두 번째는 객체지향 적으로 설계한 것 같다 이때 일반적으로 두 번째처럼 설계하면 데이터베이스에 저장할 때 각각의 테이블에 대한 insert 문을 작성해야 하고 데이터를 가져올 때도 각각 조인을 해서 가져와야 하기 때문에 여간 불편한 게 아니다.


하지만 여기서 JPA를 사용한다면?

  • jpa가 알아서 두 개에 테이블에 insert 해주고 selet 할 때도 알아서 조인해서 마치 자바 컬렉션 쓰듯이 데이터를 사용할 수 있다.

다음과 같이 사용할 수 있다.

@Entity
public class Member { 
    @Id @GeneratedValue
    @Column(name="MEMBER_ID")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "TEAM _ID")
    private Team team;
    }
    
@Entity
public class Team { 
    @Id @GeneratedValue
    @Column(name="TEAM_ID")
    private Long id;
    }

테스트 코드

public static void main(String[] args) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
    EntityManager em =emf.createEntityManager();
    EntityTransaction tx=em.getTransaction();
    tx.begin();
    try{
    	Team team =new Team(); //team 을 먼저 생성해야 member를 생성할 때 사용가능
        em.persist(team);
        Member member=new Member();
        member.setTeam(team);
        em.persist(member);
        tx.commit();
    }catch(Exception e) {
    	e.printStackTr
        tx.rollback();
    }finally {
        em.close();
    }
    emf.close();
    }
}

결과

jpa 자동테이블 생성

  • Hibernate: create sequence hibernate_sequence start with 1 increment by 1 //이부분은 시퀀스 생성
    Hibernate:
    create table Member (
       MEMBER_ID bigint not null,
        TEAM_ID bigint,
        primary key (MEMBER_ID)
    )
    Hibernate:
    create table Team (
       TEAM_ID bigint not null,
        primary key (TEAM_ID)
    )
    Hibernate:
    alter table Member 
       add constraint FKl7wsny760hjy6x19kqnduasbm 
       foreign key (TEAM_ID) 
       references Team

sql 자동생성 후 commit

  • 아래와 같이 각각의 값들이 jpa가 생성한 sql 문으로 db에 저장되는 것을 볼 수 있다.

  • Hibernate:

    call next value for hibernate_sequence

    Hibernate:

    call next value for hibernate_sequence

    Hibernate:

    /* insert jpabook.jpashop.domain.Team
        */ insert 
        into
            Team
            (TEAM_ID) 
        values
            (?)

    Hibernate:

    /* insert jpabook.jpashop.domain.Member
        */ insert 
        into
            Member
            (TEAM_ID, MEMBER_ID) 
        values
            (?, ?)

DB 데이터 확인

profile
Test로 학습 하기

0개의 댓글