Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JpaRepository find entities by logged in user context

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?

like image 477
igor milanovic Avatar asked Jun 22 '16 13:06

igor milanovic


1 Answers

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 
        }
    }

}
like image 184
ali akbar azizkhani Avatar answered Sep 28 '22 04:09

ali akbar azizkhani