I am using Spring Boot and Hibernate and JPA repositories to search data. I want to filter search results by logged in user's context. E.G. Find method to return all entities that are owned by logged in user? I have many JPA methods for filtering and I don't want to edit all of them with an additional constraint. Is it possible to do it dynamically?
You can create hibernate filter and enableFilter for session like this
/**
* @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;
}
and then enable filter using aspect
@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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With