ORM 기술 - JPA 란

johaS2·2025년 2월 4일

JPA란?

Java ORM 기술의 대표적인 표준 명세이다.
Hibernate 같은 구현체가 필요함!

JPA 등장 이유

기존 JDBC, JdbcRemplate의 단점 보완을 위해서 !
1. SQL을 직접 작성해야함
2. 데이터를 객체로 변환하는 과정이 필요
3. DB 변경 시 수정해야 할 코드가 많음

Entity 란?

Entity는 JPA의 주요 개념이다

  • 데이터베이스 테이블과 매핑되는 자바 클래스
  • 테이블의 컬럼 = 클래스의 필드
  • @Entity 어노테이션 사용

Entity 기본 구조

@Entity // 이 클래스는 DB의 테이블과 매핑됨
@Table(name="memo") // 테이블 이름 지정 (생략 가능)
@Getter
@Setter
@NoArgsConstructor
public class Memo {
    @Id // PK (기본키) 설정
    @GeneratedValue(strategy = GenerationType.IDENTITY) // Auto Increament 설정
    private Long id;   

	@Column(nullable = false) // username 컬럼 (NULL 허용 안 함)
    private String username;
    
    @Column(nullable = false, length = 500) // 최대 길이 500 설정
    private String contents;
}

Entity를 사용한 데이터 저장

// 새로운 Memo 객체 생성
Memo memo = new Memo();
memo.setUsername("조하");
memo.setContents("귀엽다");

// JPA를 이용해 DB에 저장
memoRepository.save(memo);

Repository 생성

JPA에서 기본적인 CRUD 기능을 제공하는 인터페이스

@Repository
public interface MemoRepository extends JpaRepository<Memo, Long> {
// JpaRepository<Entity,ID> 상속받으면 자동으로  DB에 연결
}

JPA 사용 전 필요한 설정

  1. build.gradle 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // JPA
  1. application.properties
# JPA 설정
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
profile
passionate !!

0개의 댓글