[Spring] CH18 스프링부트 레파지토리(저장소) - Hibernate JPA (책)

jaegeunsong97·2023년 3월 21일
0

[Fast Campus] Spring

목록 보기
31/44
post-thumbnail

아래 예제를 구현하기 전에 직접 Repository를 EntityManager로 구현해본다면 추상화된 MyRepository의 위력에 대해서 알수 있다

📕 MyRepository 구현


https://github.com/codingspecialist/Springboot-MyRepository

package shop.mtcoding.hiberpc.model;

import javax.persistence.EntityManager;
import java.util.List;

public abstract class MyRepository<T> {
    private final EntityManager em;

    public MyRepository(EntityManager em) {
        this.em = em;
    }

    public T findById(int id){
        return em.find(getEntityClass(), id);
    }
    public List<T> findAll(){
        return em.createQuery("select alias from "+getEntityName()+" alias", getEntityClass()).getResultList();
    }
    public T save(T entity){
        try {
            // Object id = getEntityClass().getMethod("getId").invoke(entity);

            Object id = em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(entity);
            if (id == null) {
                em.persist(entity);
            } else {
                entity = em.merge(entity);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to save entity: " + entity, e);
        }
        return entity;
    }

    public void delete(T entity){
        em.remove(entity);
    }

    protected abstract Class<T> getEntityClass();

    protected abstract String getEntityName();
}

📕 상속해서 사용하는 방법


package shop.mtcoding.hiberpc.model.user;

import org.springframework.stereotype.Repository;
import shop.mtcoding.hiberpc.model.MyRepository;

import javax.persistence.EntityManager;

@Repository
public class UserRepository extends MyRepository<User> {

    public UserRepository(EntityManager em) {
        super(em);
    }

    @Override
    protected Class<User> getEntityClass() {
        return User.class;
    }

    @Override
    protected String getEntityName() {
        return "User";
    }
}

📕 JpaRepository 구현


https://github.com/codingspecialist/Springboot-JpaRepository.git

Spring Boot의 JpaRepository는 JPA의 기본 메서드 외에도 CRUD(create, read, update, delete) 기능을 제공하는 메서드를 제공합니다.

JpaRepository는 이러한 메서드를 제공함으로써 개발자가 데이터 액세스 코드를 더욱 간편하게 작성할 수 있습니다.

  1. 저장/갱신 관련 메서드
  • save(S entity) : 엔티티를 저장하고 반환합니다.
  • saveAll(Iterable< S > entities) : 여러 개의 엔티티를 저장하고 반환합니다.
  1. 조회 관련 메서드
  • findById(ID id) : 주어진 기본 키로 엔티티를 검색합니다.
  • findAll() : 모든 엔티티를 검색합니다.
  • findAllById(Iterable< ID > ids) : 주어진 기본 키 목록으로 엔티티를 검색합니다.
  • count() : 엔티티의 총 개수를 반환합니다.
  1. 삭제 관련 메서드
  • deleteById(ID id) : 주어진 기본 키로 엔티티를 삭제합니다.
  • delete(T entity) : 주어진 엔티티를 삭제합니다.
  • deleteAll() : 모든 엔티티를 삭제합니다.
  • JpaRepository는 이 외에도 다양한 메서드를 제공하며, 사용자가 직접 메서드를 정의할 수도 있습니다. 또한,메서드 이름 규칙을 지켜 메서드를 작성하면, - Spring Boot가 해당 메서드를 자동으로 구현해 줍니다. 이러한 방식으로 JpaRepository를 사용하면, 데이터 액세스 코드를 더욱 쉽게 작성할 수 있습니다.

📕 JpaRepository


package shop.mtcoding.jpastudy.model;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
profile
블로그 이전 : https://medium.com/@jaegeunsong97

0개의 댓글