본문 바로가기

컴퓨터공학/Spring & Hibernate

Spring> Spring Boot> Spring Data JPA

지금까지 Entity가 Employee일 때 Dao를 만들었다.

그런데 다양한 Entity가 생긴다면 어떨까?

생긴만큼 일일히 다 DAO를 만들어줘야 하나? 그렇다면 비효율적이고 낭비이다.

Entity 종류가 많아도 어차피 다 비슷한 패턴인데 효율적으로 해결할 순 없을까?

그래서 Spring Data Jpa를 사용한다.

 

Spring Data Jpa는 entity 타입과 primary key를 입력하면

거기에 맞는 메서드를 받는 방식이다.

Dao를 추상화하여 다형성을 갖게 하는 것이다..

 

즉, Dao를 만들고 entity type과 primary key를 입력한다.

spring은 CRUD를 구현하여 제공한다.

 

Spring Data JPA는 JpaRepository 인터페이스를 제공한다..

 

지금까지는 Service 레이어에서 DAO 레이어에 요청하는 방식이었지만 

Spring Data JPA는 Service 레어어에서 Repository 레이어에 요청하는 방식이다. 

Repository 레이어에 entity 타입과 primary key를 입력하면

Repositry에서 적절한 메서드를 실행하여 결과값을 반환하는 것이다.

 

 

자세한 내용은 아래 링크에서 보자~

 

 

 

JpaRepository (Spring Data JPA 2.5.6 API)

 

JpaRepository (Spring Data JPA 2.5.6 API)

getById T getById(ID id) Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is implemented this is very likely to always return an instance and throw an EntityNotFoundException on first access. Some

docs.spring.io

 

 

JPQL을 이용한 커스텀 쿼리

Query Domain Specific Language(Query DSL)

Defining custom methods (low level coding)

은 아래 링크에서 

 

Spring Data JPA - Reference Documentation

 

Spring Data JPA - Reference Documentation

Example 109. Using @Transactional at query methods @Transactional(readOnly = true) interface UserRepository extends JpaRepository { List findByLastname(String lastname); @Modifying @Transactional @Query("delete from User u where u.active = false") void del

docs.spring.io

 

Entity type 인  Employee 과 Primary key 인 Integer를 써준다.

 

서비스에서 방금 작성한 인터페이스를 작성한다. 

Dao에서 메서드를 일일히 작성했던 방식과 다르다.

그냥 인터페이스에 타입을 적어주면 끝이다. 구현하지 않아도 됨.

그리고 서비스 레이어 메서드 위에 있던 @Transactional을 지운다.

 

 

 

 

Optionals: Patterns and Good Practices — oracle-tech