短版
我正在寻找一种让存储库类的所有findBy方法附加特定条件的方法
完整版
假设我有一个产品实体和客户实体。它们都扩展了OwnerAwareEntity,并且它们继承了ownerRef字段,该字段标识了实体的所有者(它可以是商家或合作伙伴)。我希望在运行时修改Product和Customer的findBy方法,以便附加ownerRef的附加条件。可以从用户会话中识别ownerRef值。
示例
提供公共ownerRef字段的父实体类
public class OwnerAwareEntity implements Serializable {
private String ownerRef;
}
扩展OwnerAwareEntity的客户实体
public class Customer extends OwnerAwareEntity {
private String firstname;
private String mobile ;
}
扩展OwnerAwareEntity的产品实体
public class Product extends OwnerAwareEntity {
private String code;
private String name;
}
Product&amp ;;的存储库类客户扩展OwnerAwareRepository
public interface OwnerAwareRepository extends JpaRepository {
}
public interface ProductRepository extends OwnerAwareRepository {
Product findByCode(String code );
}
public interface CustomerRepository extends OwnerAwareRepository {
Customer findByFirstname(String firstname );
}
执行此操作时,应该会产生如下所示的查询
select P from Product P where P.code=?1 and P.ownerRef='aValue'
&
select C from Customer C where C.firstname=?1 and C.ownerRef='aValue'
我应该采取什么方法来实现这种条件的附加?我只希望在父存储库是OwnerAwareRepository时发生这种追加。
答案 0 :(得分:5)
TL; DR:我使用了@Filter of Hibernate,然后创建了一个Aspect来拦截方法
定义了具有以下结构的基类实体
<强> OwnerAwareEntity.java 强>
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
@MappedSuperclass
@FilterDef(name = "ownerFilter", parameters = {@ParamDef(name = "ownerRef", type = "long")})
@Filter(name = "ownerFilter", condition = "OWNER_REF = :ownerRef")
public class OwnerAwareEntity implements Serializable{
@Column(name = "OWNER_REF",nullable = true)
private Long ownerRef;
}
我们在此实体上设置过滤器。 hibernate @Filter允许我们设置一个附加到select where子句的条件。
接下来,为OwnerAwareEntity类型的实体定义了一个基础存储库
<强> OwnerAwareRepository.java 强>
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
@NoRepositoryBean
public interface OwnerAwareRepository<T, ID extends java.io.Serializable> extends JpaRepository<T, ID> {
}
创建一个Aspect,它将拦截扩展OwnerAwareRepository的存储库中的所有方法
<强> OwnerFilterAdvisor.java 强>
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Aspect
@Component
@Slf4j
public class OwnerFilterAdvisor {
@PersistenceContext
private EntityManager entityManager;
@Pointcut("execution(public * com.xyz.app.repository.OwnerAwareRepository+.*(..))")
protected void ownerAwareRepositoryMethod(){
}
@Around(value = "ownerAwareRepositoryMethod()")
public Object enableOwnerFilter(ProceedingJoinPoint joinPoint) throws Throwable{
// Variable holding the session
Session session = null;
try {
// Get the Session from the entityManager in current persistence context
session = entityManager.unwrap(Session.class);
// Enable the filter
Filter filter = session.enableFilter("ownerFilter");
// Set the parameter from the session
filter.setParameter("ownerRef", getSessionOwnerRef());
} catch (Exception ex) {
// Log the error
log.error("Error enabling ownerFilter : Reason -" +ex.getMessage());
}
// Proceed with the joint point
Object obj = joinPoint.proceed();
// If session was available
if ( session != null ) {
// Disable the filter
session.disableFilter("ownerFilter");
}
// Return
return obj;
}
private Long getSessionOwnerRef() {
// Logic to return the ownerRef from current session
}
}
顾问程序设置为拦截扩展OwnerAwareRepository的类中的所有方法。在拦截中,当前的hibernate Session是从entityManager(当前持久化上下文)获得的,并且使用param值“ownerRef”启用过滤器。
还要创建一个配置文件以扫描顾问程序
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"com.xyz.app.advisors"})
public class AOPConfig {
}
一旦这些文件到位,您需要为需要了解所有者的实体完成以下事项
<强>依赖关系强>
此设置要求spring aop属于依赖项。您可以将以下内容添加到pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<强>优点强>
<强>注意事项强>
答案 1 :(得分:0)
您可以在Spring Data JPA方法中使用Predicate QueryDSL(或Specification)。
示例:
interface UserRepository extends CrudRepository<User, Long>, QueryDslPredicateExecutor<User> {
}
Predicate predicate = QUser.user.firstname.equalsIgnoreCase("dave")
.and(user.lastname.startsWithIgnoreCase("mathews"));
userRepository.findAll(predicate);
使用QueryDSL添加到你的pom.xml:
<dependencies>
//..
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.1.4</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.4</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
然后编译您的项目,您将获得实体的Q-classes。 更多信息是here。