filter feature during lazy-load

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

filter feature during lazy-load

Hi all,

I'm implementing filtering feature in my client application, which uses JPA to present data from the DB.
I would like to filter data which are fetched by JPA server during lazy-load, load only those entity instances that I'm interested in, and nothing else.
Since I'm novice user of JPA, I don't know all the features there exist, so I would appreciate very much if you give me a hint on an elegant (best practice) solution of this problem.

More details of my project are following:

Let's say I have three tables: Project, Employee and Task, defined like the following:

   id: int
   name: string

   id: int
   name: string

   id: int
   name: string
   employee_id: int
   project_id: id

When I log in to my client app, I choose which project I'm working with.
From then on, I would like to see only those tasks, which have been assigned to the project I've chosen on the beginning.

In Employee class I have something like this:
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "employee_id", fetch = FetchType.LAZY)
    public List<Tasks> tasks;

        public List<Tasks> getTasks(){
                return tasks;

Now, when I access to list of employees' tasks,

   Employee e = entityManager.find(Employee.class, 1);
   List<Taks> t = e.getTasks();

JPA server lazy-loads the the list of ALL tasks.

So, the question is: is there a more elegant way to load only tasks which are assigned to the active project,
than going into getTasks method, and create a JPA Query which would have something like this "... WHERE project_id = :activeProjectId ..."?

Project/Employee/Task is a simplification of the real problem, in which there exist many reference fields like "tasks",
and writing queries for each getter method is a bit tedious job, and it would render fields useless.
Can I, instead, intercept lazy-load calls of the JPA engine, and somehow add WHERE clause?

Thanks for the help in advance.