inblog logo
|
하쎄의 기술 일기장
    springboot

    영속 개체(Persistent Object)과 비영속 개체(Transient Object)의 이

    10. 영속과 비영속 개체
    하세연's avatar
    하세연
    Aug 22, 2024
    영속 개체(Persistent Object)과 비영속 개체(Transient Object)의 이
    Contents
    1. 영속(Persistent Object) 개체란?2. 비영속 개체(Transient Object)란?3. 영속화(Persistence)란?예시)
     

    1. 영속(Persistent Object) 개체란?

    💡
    영속 개체는 데이터베이스와의 연관성을 가지고 있는 개체입니다. 이 개체들은 **영속성 컨텍스트(Persistence Context)**에 의해 관리되며, 데이터베이스에 저장된 상태와 동기화됩니다. 영속성 컨텍스트는 흔히 "1차 캐시"라고도 불리며, 여기에 등록된 개체들은 자동으로 데이터베이스와 동기화됩니다. 따라서 영속 개체에 대한 변경 사항은 트랜잭션이 끝날 때 데이터베이스에 반영됩니다.
    예를 들어, JPA에서 EntityManager를 통해 엔티티(데이터베이스의 테이블에 매핑되는 객체)를 저장하면, 해당 엔티티는 영속성 컨텍스트에 의해 관리되는 영속 개체가 됩니다.

    2. 비영속 개체(Transient Object)란?

    💡
    비영속 개체는 영속성 컨텍스트와 전혀 연관이 없는 개체를 말합니다. 즉, 이 개체는 데이터베이스와 동기화되지 않으며, 데이터베이스에 저장되거나 관리되지 않습니다. 비영속 개체는 단순히 메모리 상에 존재하는 개체로, 필요 시 데이터베이스에 저장되지 않은 상태로 존재할 수 있습니다.
    예를 들어, 새롭게 객체를 생성했으나 아직 EntityManager를 통해 persist하지 않은 객체는 비영속 상태에 있습니다.

    3. 영속화(Persistence)란?

    💡
    영속화는 비영속 개체를 영속성 컨텍스트에 등록하여 영속 개체로 만드는 과정입니다. 이 과정을 통해 비영속 개체는 데이터베이스와 연관성을 가지게 되며, 그 상태가 관리되고 필요에 따라 데이터베이스에 저장됩니다.
    예를 들어, JPA에서는 EntityManager의 persist 메서드를 호출하여 비영속 객체를 영속성 컨텍스트에 등록하면, 이 객체는 영속 개체로 바뀌게 됩니다.
     

    예시)

    package shop.mtcoding.blog2.user; import lombok.Data; public class UserRequest { @Data public static class JoinDto{ private String username; private String password; private String email; // DTO -> UserObject public User toEntity(){ // insert 할때 필요 return User.builder().username(username).password(password).email(email).build(); } } @Data public static class LoginDto{ private String username; private String password; } }
     
    // Controller @PostMapping("/join") public String join(UserRequest.JoinDto joinDto) { userRepository.save(joinDto.toEntity()); return "redirect:/login-form"; } // Repository @Transactional public void save(User user) { System.out.println("담기기전 : "+ user.getId()); em.persist(user); System.out.println("담긴후 : " + user.getId()); }
    담기기전 : null Hibernate: insert into user_tb (created_at, email, password, username, id) values (?, ?, ?, ?, default) 담긴후 : 4
    Share article

    하쎄의 기술 일기장

    RSS·Powered by Inblog