使用Spring DATA实现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?
    }
}

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将从名称中找出您需要的查询。

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

因此,每个实体(实际上是每个聚合根)都有不同的存储库接口。在Account实体的存储库中,您希望执行基本的CRUD,但也希望执行特殊的查询,可能类似于

// 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配置中。

最新更新