목차

Spring Data JPA

기본 Repository Interface

public interface MyEntityRepository extends JpaRepository<MyEntity, KeyClass>, MyEntityRepositoryCustom {
}

Repository 구현

@Transactional(value = "transactionManager", readOnly = false)
public abstract class MyDomainRepositorySupport extends QueryDslRepositorySupport {
 
  // JdbcTemplate, jooq 등을 injection할 수도 있다.
 
  public MyDomainRepositorySupport(Class<?> domainClass) {
    super(domainClass);
  }
 
  @PersistenceContext(unitName = "persistenceUnitName")
  @Override
  public void setEntityManager(EntityManager entityManager) {
    super.setEntityManager(entityManager);
  }
}

모든 Repository 에는 @Transactional 붙이기

모든 Repository 에는 @Transactional을 붙여야한다.

Repository 상속 금지

Pageable 사용 금지

Pageable 대신 Slice 사용

Native Query

@Query(value = "select user_id, user_name from users ", nativeQuery = true)
List<Object[]> findUSBCandidates();

Projection

Domain Support

Audit

QueryDslRepositorySupport

Spock QueryDslRepositorySupport Mock Test

IntelliJ Spring Data Jpa Repository 자동생성

Spring Data JPA Repository

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
 
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
#parse("File Header.java")
@Repository
public interface ${EntityClass}Repository extends JpaRepository<${EntityClass}, ${EntityKey}>, QuerydslPredicateExecutor<${EntityClass}>, ${EntityClass}RepositoryCustom {
}

Spring Data JPA Repository Custom Impl

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
 
import org.springframework.data.jpa.repository.support.QueryDslRepositorySupport;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
public class ${EntityClass}RepositoryImpl extends QuerydslRepositorySupport implements ${EntityClass}RepositoryCustom {
    public ${EntityClass}RepositoryImpl() {
        super(${EntityClass}.class);
    }
 
    @PersistenceContext
    @Override
    public void setEntityManager(EntityManager entityManager) {
        super.setEntityManager(entityManager);
    }
}

Java 8 과 함께

interface CustomerRepository extends Repository<Customer, Long> {
 
  @Async
  CompletableFuture<List<Customer>> readAllBy();
 
  @Query("select c from Customer c")
  Stream<Customer> streamAllCustomers();
 
  // CRUD method using Optional
  Optional<Customer> findOne(Long id);
 
  // Query method using Optional
  Optional<Customer> findByLastname(String lastname);
}

Exists

Query 인자로 들어온 null 무시하기

(? IS NULL OR COLUMN = ?)

Projection

@Query에 SpEL 지원

@Query("select u from User u where u.age = ?#{[0]}")
List<User> findUsersByAge(int age);
 
@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

참조