我的要求是:我必须创建一个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?
}
}
答案 0 :(得分:15)
Spring Data的意思是不实现Repository。反正通常不会。相反,典型的用法是提供一个接口,Spring会注入一些你从未见过的实现。
通过扩展org.springframework.data.repository.CrudRepository
,自动处理非常基本的东西(findOne,findAll,save,delete等)。该接口为您提供方法名称。
然后,在某些情况下,您可以编写方法签名,以便Spring Data知道要获取的内容(如果您了解Grails,则在概念上类似于GORM),这称为“按方法名称创建查询”。您可以在界面中创建一个方法(复制an example from the spring data jpa documentation):
List<Person> findByLastnameAndFirstnameAllIgnoreCase(
String lastname, String firstname);
并且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);
}
你完成了,不需要实现类。 (大部分工作是编写查询并在持久化实体上添加正确的注释。您必须将存储库连接到弹簧配置中。)