Sekhon
Sekhon

Reputation: 108

Injecting a SessionScoped List in a SessionScoped bean

I have two classes

@SessionScoped
public class Department {
    private List<Employee> employees;
    //Getters and setters
}

and an employee class

@SessionScoped
public class Employee {
    private int id;
    private String name;
    //Getters and setters
}

In my controller , I retrieve the Data from the service layer and am trying to populate the Department. This is what my controller looks like.

public class MyController {
    @Inject
    private Department department;
}

I have in the past ran into trouble if I used new keyword to construct instances for CDI managed beans. Can I just create an ArrayList using new, construct the Employee instances using new, adding them to the list and then setting the list in the department bean. Could someone tell me what is the right way to populate the List of Employees (managed beans) in the managed bean Department. Remember that the scoping needs to apply. The scope could have equally well been @ViewAccessScoped

My solution is

@SessionScoped
public class Department {

    @Produces
    @SessionScoped
    private List<Employee> employees = new ArrayList();

    public add(Employee e) {
        employees.add(e);
    }
    //Getters and setters

}

Not quite sure if this is the right way to approach it, as anyone else injecting a List of employees would get this SessionScoped ArrayList??

I want to know the right way to deal with this situation

Upvotes: 0

Views: 248

Answers (1)

Marin
Marin

Reputation: 1020

The classes that represent DB like Department and Employee dont have the scope. You only need define scope in bean and after inject the diferente models (like managers). If you need relate different models (of DB) you have differente types like @OneToOne or @OneToMany or etc..

Upvotes: 2

Related Questions