“玩转”Java 系列
—————————————————————————————
1
【更多 Java – Android 资料下载,可访问尚硅谷(中国)官网 www.atguigu.com 下载区】
扩展 Spring Data JPA
在编写 Spring Data JPA 的 DAO 时,只需在接口中按规约提供方法的声明即
可。而有些业务实现无法通过声明方法或编写简单 SQL 实现,这就需要扩展
Spring Data JPA。
本文主要探讨 2 个问题:
1. 如何为某一个特定 Repository 添加自定义方法。
2. 如何为所有的 Repository 添加自定义的方法。
问题 1:为某一个特定 Repository 添加自定义方法。具体步骤:
1) 定义一个接口: 声明要添加的方法
2) 提供该接口的实现类: 类名需符合 EntityNameRepositoryImpl 格式, 并
提供方法的实现
3) 声明一个 Repository 接口, 并继承 1) 声明的接口
4) 使用
5) 注意:默认情况下, Spring Data 会在 base-package 中查找 "接口名 Impl"
作为实现类. 也可以通过 repository-impl-postfix 声明后缀
示例代码:
1) 定义一个接口: 声明要添加的方法
package com.atguigu.jpa.repository;
public interface EmployeeDao {
void method();
}
2) 提供该接口的实现类: 类名需符合 EntityNameRepositoryImpl 格式, 并
提供方法的实现
package com.atguigu.jpa.repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class EmployeeRepositoryImpl implements EmployeeDao{
//获取当前线程的 EntityManager 实例
@PersistenceContext
private EntityManager entityManager;