JPA 1

j0yy00n0·2025년 4월 8일
post-thumbnail

2025.03.26

JPA

JPA

ORM (Object-Relational Mapping)

객체(Object)와 관계형 데이터베이스(Relational Database)를 자동으로 매핑(Mapping) 해주는 기술

  • SQL 쓰지 않아도 CRUD 가능
  • JPA
  • Hibernate

JDBC (Java DataBase Connectivity)

Java Application에서 우리가 사용하는 DBMS에 접근 가능하게 하는 Programming API

  • JDBC = API + 여러 인터페이스 + DB 드라이버들

JDBC 직접 사용 시 단점

  • 자바에서 DB를 다루는 가장 원초적인 기술(가장 낮은 수준의 표준 API)
1. 드라이버 로드       → Class.forName()
2. DB 연결            → DriverManager.getConnection()
3. SQL 실행 준비       → Statement / PreparedStatement
4. SQL 실행           → executeQuery(), executeUpdate()
5. 결과 처리           → ResultSet (select일 때)
6. 자원 정리           → close()
  • SQL 쿼리와 DB 연결을 직접 관리해야 하므로 코드가 많아짐
  • 특정 DBMS와 일치하는 SQL 구문을 작성해야 함
  • SQL 구문 수행 결과를 객체에 직접 매핑해야 하므로 굉장히 코드가 많아진다.
  • 결국 유지보수성이 약화 된다.

JDBC API를 이용해 직접 SQL을 다룰 때 발생 할 수 있는 문제점

  • 데이터 변환, SQL 작성, JDBC API 코드 등의 중복 작성
    부분적으로 조회, 삽입 등을 하기 원할 때 코드가 중복 되어있기 때문에 많은 코드를 작성, 수정 해야한다.
  • SQL에 의존하여 개발
    쿼리문을 잘못 입력할 시 바로 에러가 발생한다.
  • 패러다임 불일치 (상속, 연관관계, 객체 그래프 탐색)
// 관계형 테이블 컬럼처럼 필드가 각각 따로 존재
public class EntityA {
    private int id;
    private String name;
    private int relatedEntityId;  // 외래키 필드
}

public class EntityB {
    private int id;
    private String relatedName;
}

EntityA a = new EntityA();
EntityB b = new EntityB();

// 수동 연결
a.setRelatedEntity(b);

// 관계 설정이 누락되면
a.getRelatedEntity().getRelatedName(); // ❗ NullPointerException 발생 가능
public class EntityA {
    private int id;
    private String name;
    private EntityB relatedEntity;  // 객체 자체를 참조
}

public class EntityB {
    private int id;
    private String relatedName;
}

EntityA a = entityManager.find(EntityA.class, id);
String name = a.getRelatedEntity().getRelatedName(); // NPE 발생 X
  • 동일성 보장문제

JPA(Java Persistence API)

Java 진영의 ORM(Object Relational Mapping) 기술의 표준

  • ORM 기술을 사용하기 위한 표준 인터페이스
  • Object 와 DB 테이블을 매핑하고 Java 객체 간의 관계를 토대로 SQL 을 생성 및 실행
  • 실제 구현체는 대표적으로 Hibernate 구현체 사용
  • Java Application과 JDBC 사이에서 동작, 내부적으로 JDBC API 사용

JPA 특징

  • 영속성(Persistence) Context가 엔티티(@Entity 클래스)를 생명주기를 이용해서 관리
    spring : Application Context -> IoC 컨테이너(bean 관리)
    영속성 -> HDD에 저장을 한다.
  • Native Query(JPA를 쓰는 중에도 직접 SQL 작성해서 DB에 날리는 쿼리)를 작성함으로서 SQL 구문을 DBMS에 맞게 작성할 수도 있다.
  • DBMS 별로 dialect를 제공

JPA 장점

  • DBMS 종류에 따라 달라질 수 있는 SQL 구문을 JPA 대신 판단 및 수행
  • 객체 지향과 관계지향이라는 서로 다른 패러다임 불일치 해소
  • SQL 중심이 아닌 객체지향 패러다임 중심의 개발이 가능
  • 개발자가 직접 SQL 구문을 작성하지 않아도 SQL 구문을 직접 작성
  • Cache 사용을 통해 성능 최적화로 트랜젝션 처리시간의 효율

JPA 단점

  • 너무 복잡한 SQL 구문을 작성하기에는 적합하지 않다. -> Native Query로 해결
  • JPA의 연관관계 특성을 이해하지 못 하면 성능 저하가 발생할 수 있다.
  • 복잡한 동적 SQL 구문 같은 경우에는 순수 JPA만 사용해서 처리하기 힘들다.

JPA LifeCycle

Persistence Context를 통해 Entity 객체를 저장, 보관, 관리한다.

  • Entity : @Entity , @Table , @Id , @Column과 같은 어노테이션을 통해 SQL이 아닌 DB 테이블과 매칭되는 클래스
  • JPA가 엔티티의 상태 변화 시 자동으로 호출하는 콜백 메서드들 등록할 수 있다.

JPA 의 Persistence Context


엔티티 매니저가 엔티티를 저장, 관리, 보관하는 공간

  • Entity 매니저가 생성될 때 하나의 Persistence Context가 만들어진다.
  • 1차 캐시
    Persistence Context 내부에 Map 형태로 관리되는 캐시(Key : @Id, Value : Entity 인스턴스) -> 임시 Database
    엔티티 저장
    1차 캐시 영역에 있는 Entity는 캐시에서 바로 불러와 조회의 성능을 향상
  • 동일성 보장
  • 트랜젝션을 지원하는 쓰기 지연 SQL 저장소
    Entity Manager는 트렌젝션을 Commit 하기 전까지 DB에 반영하지 않고 쓰기 지연 SQL 저장소에 보관
    INSERT, UPDATE, DELETE 쿼리 임시 저장
    DB의 반영하는 방법 : flush() 메소드 호출, Commit(), JPQL 수행
  • 변경 감지 : Entity 인스턴스의 수정이 발생하면 DB 에 자동으로 반영하는 것

Entity의 생명주기

  • 비영속 : Entity가 컨텍스트와 전혀 관계 없는 상태
  • 영속 : Entity가 컨텍스트에 저장 된 상태
  • 준영속 : 컨텍스트에 저장 되었다가 분리 된 상태
  • 삭제 : Entity가 삭제 된 상태
  • 병합 : 준영속 상태의 Entity가 다시 영속 상태로 변경

JPA 구현체 HIBERNATE의 중요한 요소 2가지

️EntityManager

공장을 통해 생성이 되며 엔티티를 관리하는 역할

  • 엔티티를 저장하는 메모리 상의 데이터베이스
  • 저장, 수정, 삭제, 조회 등 엔티티와 관련 된 모든 일은 담당
  • 내부에 Persistence Context (영속성 컨텍스트)를 가지고 있다.
  • thread-safe 하지 않기 때문에 request-scope 와 일치하는 생명주기를 갖게 해야 한다.
    요청을 할 때마다 생성하게 된다.

EntityManagerFactory

엔티티 매니저를 생성할 수 있는 기능을 제공하는 팩토리 클래스

  • thread-safe 하기 때문에 application-scope 와 일치하는 생명주기를 통해 자원을 관리해야 한다.
    application-scope -> singleton 인스턴스로 관리한다는 의미
  • 무겁고 초기화 비용이 많이 든다.

IntelliJ Database 연결

  • application.yml 파일 안에 Database 연결설정을 한다.
spring:
  jpa:
    hibernate:
      ddl-auto: DDL명령어
    properties:
      hibernate:
        show_sql: SQL출력여부 (true/false)
        format_sql: SQL형식화여부 (true/false)

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/데이터베이스이름
    username: 연결계정이름
    password: 연결계정비밀번호

  • 오른쪽에 데이터베이스 버튼을 누르고 +를 누른다.
  • 자신이 사용하는 DBMS를 선택한다.
  • Name, User, Password 작성하고 Port:3306으로 두고 연결 테스트를 누른다.
  • 드라이버 설치하라고 뜨게 되면 설치하면 된다.
  • 연결이 성공되면 적용을 누르고 확인을 누른다.
  • 연결된 계정에서 전체 스키마를 눌러서 이미 데이터베이스에 작성한 테이블들을 가지고 온다.
  • MySQL Workbench에 들어가서 관리자 계정에 들어간다.
CREATE DATABASE 데이터베이스명;
GRANT ALL PRIVILEGES ON 데이터베이스명.* TO '계정이름'@'%';
  • 명령어를 입력해서 권한을 준다.
  • 다시 IntelliJ 들어가고 디비에서 새로고침을 누르게 되면 새로운 데이터베이스가 생긴다.
  • 어플리케이션으로 맞춰두고 실행을 시킨다.
  • 실행을 해보면 Entity를 기반으로 Hibernate가 알아서 테이블을 생성해준다.
  • 다시 IntelliJ 데이터베이스 부분에서 새로고침하면 테이블이 생성되어있다.
  • 데이터를 입력하기 위해서는 Postman을 사용하거나 http요청을 사용하여 확인을 할 수 있다.

Test code

JUnit Test code 작성 방법

  • IntelliJ의 src > test 디렉토리 내에 test code 클래스 생성
  • 테스트할 메서드에 @Test 어노테이션을 붙여 작성
  • 메서드는 전체 실행이 아닌 개별 실행도 가능
  • 테스트 메소드 안은 given(사전 조건), when(테스트 할 시점), then(테스트에서 기대하는 결과) 형식으로 작성한다.
public class 테스트클래스명{

	private 메인디렉토리클래스명 테스트할메인디렉토리의인스턴스명;
    
    @BeforeEach
    <!-- 각 테스트 메서드 실행 전에 호출됨 → 공통 초기화 작업 수행 -->
    void setUp() {
    	<!-- 테스트 대상 객체 생성 -->
        테스트할메인디렉토리의인스턴스명 = new 메인디렉토리클래스명();
    }
    
    @AfterEach
    <!-- 각 테스트 메서드 실행 후 호출됨 → 정리/후속 작업 수행 -->
    void tearDown() {
        // 출력할 구문
    }
    
    @DisplayName("테스트 이름을 지정")
    @Test
    void 테스트메서드이름(){

        <!-- given : 사전 조건 -->
        자료형 변수1 = 값1;
        자료형 변수2 = 값2;

        <!-- when : 테스트 할 시점 -->
        자료형 결과변수 = 테스트할메인디렉토리의인스턴스명.테스트할인스턴스의메서드(매개변수1, 매개변수2);

        <!-- then : 테스트에서 기대하는 결과) -->
        assertEquals(기대예상값, 결과변수);

    }
}
@BeforeAll : 테스트 클래스 전체가 시작되기 전 한 번만 실행되는 초기 설정 메소드 정의 (app-scope), static 필수
@BeforeEach : 매 테스트 메서드 실행 전에 공통 준비 작업 수행 (초기화 등)
@AfterAll : 매 테스트 메서드 실행 후 정리 작업 수행 (리소스 정리, 롤백 등)
@AfterEach : 테스트 클래스 전체가 끝난 후 한 번만 실행되는 정리 메서드, static 필수

Persistence Context 작성

  • JPA JAVA 프로젝트 환경에서 작성
  • hibernate 의존성 추가 -> 엔티티 매니저, 팩토리 클래스 사용 가능
  • hibernate persistence.xml 파일 작성
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.2">
    
    <!-- persistence유닛별칭 -->
    <persistence-unit name="persistence유닛이름">
        
        <!-- JPA로 관리할 엔티티 클래스 등록 -->
        <class>엔티티패키지경로.엔티티클래스명</class>

        <properties>
            <!-- JDBC 드라이버 설정 -->
            <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>

            <!-- DB 연결 정보 -->
            <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/DB이름"/>
            <property name="jakarta.persistence.jdbc.user" value="DB사용자명"/>
            <property name="jakarta.persistence.jdbc.password" value="DB비밀번호"/>

            <!-- 콘솔에 SQL 출력 여부 -->
            <!-- sql 화면 출력 -->
            <property name="hibernate.show_sql" value="true"/>
            <!-- sql 정렬 출력 -->
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>

</persistence>
  • 필요 시 lombok 의존성 추가
    lombok : DTO 클래스(기본생성자, 모든필드생성자, getter, setter, toString)를 자동으로 생성
  • Entity Manger 라이프사이클 테스트
public class JPAEntityManagerLifecycleTest {

    <!-- EntityManagerFactory는 애플리케이션 전체에서 하나만 생성
    private static EntityManagerFactory entityManagerFactory;

    <!-- EntityManager는 테스트 메서드마다 새로 생성
    private static EntityManager entityManager;

    @BeforeAll
    <!-- 테스트 클래스 실행 전, 영속성 유닛을 통해 팩토리 생성 (application-scope)
    public static void initFactory() {
        entityManagerFactory =
                Persistence.createEntityManagerFactory("Persistence유닛이름");
    }

    @BeforeEach
    <!-- 각 테스트 전에 EntityManager 생성 (request-scope)
    public void initManager() {
        entityManager = entityManagerFactory.createEntityManager();
    }

    @AfterEach
    <!-- 각 테스트 후 EntityManager 종료
    public void closeManager() {
        entityManager.close();
    }

    @AfterAll
    <!-- 테스트 클래스 전체 종료 후 EntityManagerFactory 종료
    public static void closeFactory() {
        entityManagerFactory.close();
    }

    @DisplayName("EntityManagerFactory와 EntityManager 해시코드 확인 - 테스트1")
    @Test
    public void testEntityManagerLifeCycle1() {
        System.out.println("entityManagerFactory.hashCode() = "
                + entityManagerFactory.hashCode());
        System.out.println("entityManager.hashCode() = " + entityManager.hashCode());
    }

    @DisplayName("EntityManagerFactory와 EntityManager 해시코드 확인 - 테스트2")
    @Test
    public void testEntityManagerLifeCycle2() {
        System.out.println("entityManagerFactory.hashCode() = "
                + entityManagerFactory.hashCode());
        System.out.println("entityManager.hashCode() = " + entityManager.hashCode());
    }
}
  • JPA Entity 작성
<!-- lombok 어노테이션으로 생성자, getter/setter 등 자동 생성 -->
@Entity(name = "엔티티_논리이름") // 선택: 다른 클래스와 이름 겹칠 때
@Table(name = "테이블_이름")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter  <!-- 실제 서비스에서는 setter는 제한적으로 사용하는 것이 좋음 -->
@ToString
public class 클래스명 {

    @Id
    @Column(name = "기본키_컬럼명")
<!-- @GeneratedValue(strategy = GenerationType.IDENTITY)  기본키 자동 생성 시 사용 -->
    private 기본키_자료형 필드명;

    @Column(name = "컬럼명1")
    private 자료형 필드명1;

    @Column(name = "컬럼명2")
    private 자료형 필드명2;

}
  • 엔티티 매니저 테스트
public class EntityManagerCRUDTestTemplate {

    private static EntityManagerFactory entityManagerFactory;
    private static EntityManager entityManager;

    @BeforeAll
    public static void initFactory() {
        <!-- persistence.xml의 persistence-unit 이름 사용 -->
        entityManagerFactory = Persistence.createEntityManagerFactory("퍼시스턴스유닛이름");
    }

    @BeforeEach
    public void initManager() {
        entityManager = entityManagerFactory.createEntityManager();
    }

    @AfterAll
    public static void closeFactory() {
        entityManagerFactory.close();
    }

    @AfterEach
    public void closeManager() {
        entityManager.close();
    }
    
    <!-- 여러 테스트 -->
}
<!-- 기본키로 엔티티 조회 테스트 -->
	@Test
    public void selectEntityByIdTest() {
        // given
        자료형 기본키필드명 = 1;

        // when
        엔티티클래스명 entity변수명 = entityManager.find(엔티티클래스명.class, 기본키필드명);

        // then
        Assertions.assertNotNull(entity변수명);
        Assertions.assertEquals(기본키필드명, entity변수명.get기본키필드명());
        System.out.println("entity = " + entity변수명);
    }
    
<!-- 새로운 엔티티 추가 테스트 -->
	@Test
    public void insertNewEntityTest() {
        // given
        엔티티클래스명 entity변수명 = new 엔티티클래스명();
        entity변수명.setField1("특정값1");
        entity변수명.setField2(특정값2);
        entity변수명.setField3(특정값3);

        // when
        EntityTransaction transaction변수명 = entityManager.getTransaction();
        <!-- 트랜젝션 시작 선언 -->
        transaction변수명.begin();
        
        try {
        <!-- Persistence Context에 등록 -->
            entityManager.persist(entity변수명);
            transaction변수명.commit();
        } catch (Exception e) {
        <!-- 실패 시 롤백 -->
            transaction변수명.rollback();
            e.printStackTrace();
        }

        <!-- then : Persistence Context에 포함되었는지 확인 -->
        Assertions.assertTrue(entityManager.contains(entity변수명));
    }

<!-- 엔티티 수정 테스트 -->
	@Test
    public void updateEntityFieldTest() {
        // given
        자료형 기본키필드명 = 1;
        엔티티클래스명 entity변수명 = entityManager.find(엔티티클래스명.class, 기본키필드명);
        String 변경값변수명 = "변경값";

        // when
        EntityTransaction transaction변수명 = entityManager.getTransaction();
        transaction변수명.begin();
        try {
            entity.set필드명(변경값변수명);
            transaction변수명.commit();
        } catch (Exception e) {
            transaction변수명.rollback();
            e.printStackTrace();
        }

        // then
        Assertions.assertEquals(변경값변수명, entityManager.find(엔티티클래스명.class, 기본키필드명).get필드명());
    }
    
<!-- 엔티티 삭제 테스트 --> 
	@Test
    public void deleteEntityTest() {
        // given
        엔티티클래스명 entity변수명 = entityManager.find(엔티티클래스명.class, 기본키필드명값);

        // when
        EntityTransaction transaction변수명 = entityManager.getTransaction();
        transaction변수명.begin();
        try {
            entityManager.remove(entity변수명);
            transaction변수명.commit();
        } catch (Exception e) {
            transaction변수명.rollback();
            e.printStackTrace();
        }

        // then
        EntityClass 삭제된entity변수명 = entityManager.find(엔티티클래스명.class, 기본키필드명값);
        Assertions.assertNull(삭제된entity변수명);
    }
  • Entity 라이프 사이클 테스트
public class Entity 라이프 사이클 테스트 {

    private static EntityManagerFactory entityManagerFactory;
    private static EntityManager entityManager;

    @BeforeAll
    public static void initFactory() {
        <!-- persistence.xml의 persistence-unit 이름 사용 -->
        entityManagerFactory = Persistence.createEntityManagerFactory("퍼시스턴스유닛이름");
    }

    @BeforeEach
    public void initManager() {
        entityManager = entityManagerFactory.createEntityManager();
    }

    @AfterAll
    public static void closeFactory() {
        entityManagerFactory.close();
    }

    @AfterEach
    public void closeManager() {
        entityManager.close();
    }
    
    <!-- 여러 테스트 -->
}
<!-- 비영속 상태 비교 테스트 -->
	@Test
    public void testTransientState() {
    	<!-- given -->
        엔티티클래스명 영속엔티티변수명 = entityManager.find(엔티티클래스명.class, 특정값);

		<!-- 비영속 상태의 새 엔티티 생성 (DB 연결 X) -->
        엔티티클래스명 비영속엔티티변수명 = new 엔티티클래스명();
        비영속엔티티변수명.set필드명1(영속엔티티변수명.get필드명1());
        비영속엔티티변수명.set필드명2(영속엔티티변수명.get필드명2());

		<!-- then : 두 객체는 같은 값을 가지더라도 다른 인스턴스이므로 주소값이 다름,값은 false-->
        Assertions.assertFalse(영속엔티티변수명 == 비영속엔티티변수명);
    }
	
<!-- 같은 엔티티 조회 시 동일성 보장 테스트 -->
<!-- 엔티티 매니저가 엔티티를 조회할 때 
1차 캐시(영속성 컨텍스트)에 이미 존재하는 엔티티라면
DB에 접근하지 않고 기존 객체를 반환
→ 같은 PK로 조회하면 동일 객체(==) 반환됨 -->
	@Test
    public void testPersistenceContextCache() {
    
    	<!-- given : 같은 기본키로 두 번 조회 -->
    	엔티티클래스명 엔티티1 = entityManager.find(엔티티클래스명.class, 기본키값);
    	엔티티클래스명 엔티티2 = entityManager.find(엔티티클래스명.class, 기본키값);

		<!-- then : 두 객체는 동일 인스턴스 → 주소값 비교 결과 true -->
        Assertions.assertTrue(엔티티1 == 엔티티2);
    }
    
<!-- 영속 객체 추가 후 동일성 비교 테스트 -->
	@Test
    public void testPersistedObjectEquality() {
    	<!-- given : 새로운 엔티티 인스턴스 생성 및 값 설정 -->
        엔티티클래스명 엔티티변수명 = new 엔티티클래스명();
        엔티티변수명.set필드1(특정값1);
        엔티티변수명.set필드2("특정값2");

		<!-- when : 엔티티를 영속성 컨텍스트에 등록 -->
        entityManager.persist(엔티티변수명);

		<!-- 이후 같은 특정값으로 조회 -->
        <!-- 트렌젝션이 적용되지 않았기 때문에, 쿼리문은 발생하지 않는다. -->
        엔티티클래스명 조회할엔티티변수명 = entityManager.find(엔티티클래스명.class, 특정값1);
        
        <!-- then : persist() 이후 동일 영속성 컨텍스트 안에서는 같은 객체 반환 → 주소 같음 -->
        Assertions.assertTrue(엔티티변수명 == 조회할엔티티변수명);
    }
    
<!-- 영속 객체 수정 후 커밋 테스트 -->
	@Test
    public void testModifyAndCommit() {
        엔티티클래스명 엔티티변수명 = new 엔티티클래스명();
        엔티티변수명.set필드1(특정값1);
        엔티티변수명.set필드2("특정값2");

        EntityTransaction 트랜잭션변수 = entityManager.getTransaction();
    	트랜잭션변수.begin();

        try {
        entityManager.persist(엔티티변수명);           // 영속성 컨텍스트 등록
        엔티티변수명.set필드2("수정값");                // 필드 값 변경
        트랜잭션변수.commit();                        // 커밋 시점에 update 쿼리 발생
        } catch (Exception e) {
            트랜잭션변수.rollback();
        }

        엔티티클래스명 조회할엔티티 = entityManager.find(엔티티클래스명.class, 특정값);
        Assertions.assertEquals("수정값", 조회할엔티티.get필드2());
    }

<!-- detach 준영속 테스트 -->
	@Test
    public void testDetach() {
    	<!-- given : 서로 다른 특정값의 두 엔티티 조회 → 모두 영속 상태 -->
        엔티티클래스명 영속엔티티1 = entityManager.find(엔티티클래스명.class, 특정값1);
    	엔티티클래스명 영속엔티티2 = entityManager.find(엔티티클래스명.class, 특정값2);

		<!-- when : 두 번째 엔티티를 detach 처리 → 준영속 상태로 전환됨 -->
        entityManager.detach(영속엔티티2);

        영속엔티티1.set필드2(수정값);
    	영속엔티티2.set필드2(수정값);

		<!-- then : 첫 번째 영속 상태 -> DB에 반영
        	두 번째 준영속 상태 -> DB에 반영되지 않음 -->
        Assertions.assertEquals(수정값, entityManager.find(엔티티클래스명.class, 특정값1).get필드2());
    	Assertions.assertNotEquals(수정값, entityManager.find(엔티티클래스명.class, 특정값2).get필드2());
    }
    
<!-- clear 준영속 전체 테스트 -->  
	@Test
    public void testClear() {
        <!-- given : 영속 상태로 두 엔티티 조회 -->
        엔티티클래스명 영속엔티티1 = entityManager.find(엔티티클래스명.class, 특정값1);
        엔티티클래스명 영속엔티티2 = entityManager.find(엔티티클래스명.class, 특정값2);

		<!-- when : clear() 호출 → 모든 엔티티가 준영속 상태로 전환 -->
        entityManager.clear();

        <!-- clear 이후 필드 값을 변경 → JPA는 더 이상 추적하지 않음 -->
        영속엔티티1.set필드2(수정값);
        영속엔티티2.set필드2(수정값);

        <!-- then : 변경된 값은 DB에 반영되지 않음 → DB에서 다시 조회한 값과 다를 수 있음 -->
    	Assertions.assertNotEquals(수정값, entityManager.find(엔티티클래스명.class, 특정값1).get필드2());
    	Assertions.assertNotEquals(수정값, entityManager.find(엔티티클래스명.class, 특정값2).get필드2());
    }
    
<!-- close 테스트 -->
	@Test
    public void testClose() {
        엔티티클래스명 영속엔티티1 = entityManager.find(엔티티클래스명.class, 특정값1);
        엔티티클래스명 영속엔티티2 = entityManager.find(엔티티클래스명.class, 특정값2);

		<!-- when : EntityManager 종료 → 영속성 컨텍스트 소멸 → 모든 엔티티는 준영속 상태가 됨 -->
        entityManager.close();

        <!--  영속성 컨텍스트와는 무관하게 자바 객체의 필드는 수정 가능 -->
        영속엔티티1.set필드2(수정값);
        영속엔티티2.set필드2(수정값);

        <!-- then : 객체 내 필드는 수정되었지만 DB에는 반영되지 않음 -->
        Assertions.assertEquals(수정값, 영속엔티티1.get필드2());
        Assertions.assertEquals(수정값, 영속엔티티2.get필드2());
    }
    
<!-- 엔티티 삭제 테스트 -->
	@Test
    public void testRemoveEntity() {
        <!-- given : 삭제할 엔티티 조회 (영속 상태) -->
    	엔티티클래스명 삭제대상엔티티 = entityManager.find(엔티티클래스명.class, 특정값);

        <!-- when : 해당 엔티티를 영속성 컨텍스트에서 제거 -->
    	entityManager.remove(삭제대상엔티티);

        <!-- then : 동일한 PK로 다시 조회했을 때 null이어야 함 (삭제 확인) -->
    	엔티티클래스명 재조회할엔티티 = entityManager.find(엔티티클래스명.class, 특정값);
    	Assertions.assertEquals(null,재조회엔티티);
    }
profile
잔디 속 새싹 하나

0개의 댓글