【问题标题】:Spring Data JPA: Implementing Custom Repository Behavior with SpecificationsSpring Data JPA:使用规范实现自定义存储库行为
【发布时间】:2015-03-15 17:16:20
【问题描述】:
【问题讨论】:
标签:
java
spring
jpa
spring-data
spring-data-jpa
【解决方案1】:
我想灵感的主要来源可能是SimpleJpaRepository 如何处理规范。需要查看的关键点是:
【解决方案2】:
这没有使用规范,所以不确定它是否与您相关,但我能够注入自定义行为的一种方法如下,
-
基本结构:如下
我。为以通用父实体建模的实体类集创建通用接口。请注意,这是可选的。就我而言,我需要这种层次结构,但这不是必需的
public interface GenericRepository<T> {
// add any common methods to your entity hierarchy objects,
// so that you don't have to repeat them in each of the children entities
// since you will be extending from this interface
}
二。从通用(第 1 步)和 JPARepository 扩展特定存储库
public interface MySpecificEntityRepository extends GenericRepository<MySpecificEntity>, JpaRepository<MySpecificEntity, Long> {
// add all methods based on column names, entity graphs or JPQL that you would like to
// have here in addition to what's offered by JpaRepository
}
三。在您的服务实现类中使用上述存储库
-
现在,Service 类可能看起来像这样,
public interface GenericService<T extends GenericEntity, ID extends Serializable> {
// add specific methods you want to extend to user
}
-
通用实现类可以如下,
public abstract class GenericServiceImpl<T extends GenericEntity, J extends JpaRepository<T, Long> & GenericRepository<T>> implements GenericService<T, Long> {
// constructor takes in specific repository
public GenericServiceImpl(J genericRepository) {
// save this to local var
}
// using the above repository, specific methods are programmed
}
-
具体实现类可以
public class MySpecificEntityServiceImpl extends GenericServiceImpl<MySpecificEntity, MySpecificEntityRepository> implements MySpecificEntityService {
// the specific repository is autowired
@Autowired
public MySpecificEntityServiceImpl(MySpecificEntityRepository genericRepository) {
super(genericRepository);
this.genericRepository = (MySpecificEntityRepository) genericRepository;
}
}