0

私の要件は次のとおりです: 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?
    }
}
4

1 に答える 1

18

Spring Data のポイントは、リポジトリを実装しないことです。とにかく、通常はそうではありません。代わりに、典型的な使用法は、インターフェースを提供し、Spring が目に見えない実装を注入することです。

非常に基本的なもの (findOne、findAll、save、delete など) は、org.springframework.data.repository.CrudRepository. そのインターフェースは、メソッド名を提供します。

次に、Spring Data がフェッチするものを認識できるようにメソッド シグネチャを記述できる場合があります (Grails を知っている場合は GORM の概念に似ています)、これを「メソッド名によるクエリ作成」と呼びます。次のようなインターフェースでメソッドを作成できます(Spring Data JPAのドキュメントから例をコピーします):

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);
}

これで完了です。実装クラスは必要ありません。(ほとんどの作業は、クエリを作成し、永続エンティティに適切な注釈を付けることです。また、リポジトリを Spring 構成に接続する必要があります。)

于 2013-03-22T14:57:31.303 に答える