使用Spring DATA实现DAO

Pau*_*tin 0 spring spring-data spring-data-jpa

我的要求是:我必须创建一个AccountRepository接口,我必须在我的AccountRepositoryImpl本身实现所有方法,所以我该怎么做呢?

例:

1)界面

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

2)实施?

public class AccountRepositoryImpl implements AccountRepository
{
    public List<Account> getAllAccounts() {
        // now what?
    }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*hes 15

Spring Data的重点是你没有实现Repository.反正通常不会.相反,典型的用法是提供一个接口,Spring会注入一些你从未见过的实现.

最基本的东西(findOne,findAll,save,delete等)通过扩展自动处理org.springframework.data.repository.CrudRepository.该接口为您提供方法名称.

然后,在某些情况下,您可以编写方法签名,以便Spring Data知道要获取的内容(如果您了解Grails,则在概念上类似于GORM),这称为"按方法名称创建查询".您可以在界面中创建一个方法,如下所示(复制spring data jpa文档中的示例):

List<Person> findByLastnameAndFirstnameAllIgnoreCase(
    String lastname, String firstname);
Run Code Online (Sandbox Code Playgroud)

和Spring Data将从名称中找出您需要的查询.

最后,为了处理复杂的情况,您可以提供一个Query注释,指定您要使用的JPQL.

因此,每个实体都有不同的存储库接口.您希望执行基本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);
}
Run Code Online (Sandbox Code Playgroud)

你完成了,不需要实现类.(大多数工作是编写查询并在持久化实体上添加正确的注释.您必须将存储库连接到弹簧配置中.)