복붙노트

[SPRING] Spring 데이터를 사용하여 DAO 구현하기

SPRING

Spring 데이터를 사용하여 DAO 구현하기

내 요구 사항은 다음과 같습니다. AccountRepository 인터페이스를 만들어야하고 내 AccountRepositoryImpl 자체에서 모든 메서드를 구현해야합니다. 어떻게이 작업을 수행 할 수 있습니까?

예:

1) 인터페이스

/* this is the interface */  
public interface AccountRepository extends JpaRepository
{
    List<Account> getAllAccounts();
}

2) 구현?

public class AccountRepositoryImpl implements AccountRepository
{
    public List<Account> getAllAccounts() {
        // now what?
    }
}

해결법

  1. ==============================

    1.Spring 데이터의 요점은 저장소를 구현하지 않는다는 것입니다. 어쨌든 보통은 아닙니다. 대신 전형적인 사용법은 당신이 인터페이스를 제공하고 Spring은 결코 볼 수없는 구현을 주입한다는 것이다.

    Spring 데이터의 요점은 저장소를 구현하지 않는다는 것입니다. 어쨌든 보통은 아닙니다. 대신 전형적인 사용법은 당신이 인터페이스를 제공하고 Spring은 결코 볼 수없는 구현을 주입한다는 것이다.

    매우 기본적인 것들 (findOne, findAll, save, delete 등)은 org.springframework.data.repository.CrudRepository를 확장하여 자동으로 처리됩니다. 이 인터페이스는 메소드 이름을 제공합니다.

    그런 다음 Spring 데이터가 가져올 내용을 알 수 있도록 메소드 서명을 작성할 수있는 경우가 있습니다 (Grails를 알고 있으면 GORM과 개념이 비슷합니다).이를 메소드 이름 별 쿼리 작성이라고합니다. 다음과 같이 인터페이스에서 메소드를 생성 할 수 있습니다 (스프링 데이터 JP 문서의 예제 복사).

    List<Person> findByLastnameAndFirstnameAllIgnoreCase(
        String lastname, String firstname);
    

    Spring Data는 이름에서 필요한 쿼리를 찾습니다.

    마지막으로 복잡한 경우를 처리하기 위해 사용할 JPQL을 지정하는 Query 주석을 제공 할 수 있습니다.

    따라서 각 엔티티마다 서로 다른 저장소 인터페이스가 있습니다. 기본 CRUD를 수행하고 싶지만 실행하고자하는 특별한 쿼리가있는 Account 엔티티 저장소

    // crud methods for Account entity, where Account's PK is 
    // an artificial key of type Long
    public interface AccountRepository extends CrudRepository<Account, Long> {
        @Query("select a from Account as a " 
        + "where a.flag = true " 
        + "and a.customer = :customer")
        List<Account> findAccountsWithFlagSetByCustomer(
            @Param("customer") Customer customer);
    }
    

    구현 클래스가 필요하지 않습니다. (대부분의 작업은 쿼리를 작성하고 영구적 인 엔티티에 올바른 주석을 넣는 것입니다. 그리고 리포지토리를 스프링 구성에 연결해야합니다.)

  2. from https://stackoverflow.com/questions/15571608/using-spring-data-to-implement-dao by cc-by-sa and MIT license