0

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

Sekhon
  • 108
  • 1
  • 10
  • 2
    The general design problem here is that your entities are made managed beans. In fact, only the `MyController` is suitable candidate to be a managed bean. This is going to be a long and somewhat subjective story which fits technically better on programmers.se, but you may assume this answer to apply on your case as well: http://stackoverflow.com/questions/25431338/why-shouldnt-entity-bean-be-managed-by-jsf-framework/ – BalusC Aug 27 '14 at 08:43
  • BalusC, These are not JPA entities, but more like a simplified Model object that is used to represent the information that goes on to the view. You could go so far to say that the Objects that are returned by the DAO or the service layer need to be translated to a simple model objects for the view, if that makes sense. – Sekhon Aug 27 '14 at 14:51
  • Ah, the good 'ol DTO. Well, perhaps ... It still feels wrong. Alas, subjective matter. Try programmers.se or an "old fashioned" discussion forum. Stack Overflow as being a Q&A site isn't suitable for discussions. – BalusC Aug 27 '14 at 18:30
  • BalusC, could you still advise the "how" to do it part? Let alone best practise, what would work? – Sekhon Aug 28 '14 at 01:01

1 Answers1

2

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

Marin
  • 1,010
  • 1
  • 10
  • 37