Thursday, July 5, 2018

JpaRepository find entities by logged in user context

Leave a Comment

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?

1 Answers

Answers 1

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 Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment