igo*_*vic 9 spring hibernate jpa
我使用Spring Boot和Hibernate以及JPA存储库来搜索数据.我想通过登录用户的上下文来过滤搜索结果.EG Find方法返回登录用户拥有的所有实体?我有许多JPA方法用于过滤,我不想用额外的约束来编辑所有这些方法.有可能动态地做吗?
您可以像这样为会话创建hibernate过滤器和enableFilter
/**
* @author ali akbar azizkhani
*/
@Entity
@Table(name = "post")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Filter(name = "filter",condition = "created_By=:user")
@FilterDef(name = "filter", defaultCondition = "deleted=0",parameters = {
@ParamDef(name = "user",type = "string")
})
public class Post {
@Id
@GeneratedValue
Long id;
@Column(name = "title")
String title;
@Column(name = "deleted")
boolean deleted = false;
@OneToMany(mappedBy = "post")
Set<PostComment> commentList = new HashSet<>();
@Column(name = "createdBy")
String createdBy;
}
Run Code Online (Sandbox Code Playgroud)
然后使用方面启用过滤器
@Aspect
@Component
class EnableFilterAspect {
@AfterReturning(
pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))",
returning = "retVal")
public void getSessionAfter(JoinPoint joinPoint, Object retVal) {
if (retVal != null && EntityManager.class.isInstance(retVal)) {
Session session = ((EntityManager) retVal).unwrap(Session.class);
session.enableFilter("filter").setParameter("user","admin");//get from security context holder
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
426 次 |
| 最近记录: |