【问题标题】:using Spring DATA to implement DAO使用 Spring DATA 实现 DAO
【发布时间】:2013-03-12 09:13:29
【问题描述】:

我的要求是:我必须创建一个 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 spring-data spring-data-jpa


【解决方案1】:

Spring Data 的重点是您不要实现存储库。反正通常不会。相反,典型的用法是您提供一个接口,然后 Spring 注入一些您从未见过的实现。

通过扩展org.springframework.data.repository.CrudRepository 会自动处理非常基本的内容(findOne、findAll、保存、删除等)。该接口为您提供方法名称。

然后在某些情况下,您可以编写方法签名以便 Spring Data 知道要获取什么(如果您知道 Grails,则在概念上类似于 GORM),这称为“通过方法名称创建查询”。你可以像这样在接口中创建一个方法(复制an example from the spring data jpa documentation):

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

Spring Data 会从名称中找出您需要的查询。

最后,为了处理复杂的情况,您可以提供一个查询注释来指定您要使用的 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);
}

你就完成了,不需要实现类。 (大部分工作是编写查询并将正确的注释放在持久实体上。您必须将存储库连接到您的 spring 配置中。)

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 2012-09-25
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2011-11-23
    • 2023-03-25
    相关资源
    最近更新 更多