2

I am trying to create a Java EE Web Application with JSF 2, Spring and Hibernate. I'm fairly new to this stack, so I need some help on best practices in organizing an application.

My initial objective is simple, a User logins in, and her session is not closed until she logs out. Here is what I have come up with so far:

  • User entity class, annotated with @Entity so that it is persisted. Not registered as a JSF or managed bean. Simple POJO with private fields (name, surname etc) and with accessors.

  • An interface for a DAO to interact with the User class: getUserById(), saveUser() etc.

  • An implementation of the DAO. Marked with Spring's @Repository and with Hibernate's SessionFactory @Autowired and added in ApplicationContext via component-scan.

Now, for a user browsing the site, I believe I should not create a session-scoped bean from my User class, is that correct? I think the best practice would be to never directly touch the User class, only through DAO.

So, do I need to have another bean UserManaged (probably ManagedBean and session scoped) that duplicates the fields of the User class; and use that in my JSF files? So, the beans user that are created when user interacts with the website should be handled by JSF, and the rest by Spring? But wouldn't that duplication break the DRY principle, having the same fields as in User in another UserManaged class?

ustun
  • 6,941
  • 5
  • 44
  • 57
  • Or in other words, is JSF beans only to be used for the UI of the site? And non-UI beans, used for persistence to be handled via Spring? – ustun Oct 19 '11 at 08:02
  • These might be related, too: http://stackoverflow.com/questions/4173330/jsf-backing-bean-and-hibernate-entity-same-class http://stackoverflow.com/questions/4808457/why-cant-i-have-an-entity-bean-as-a-jsf-backing-bean-in-jee-5 http://stackoverflow.com/questions/746047/jsf-backing-bean-structure-best-practices – ustun Oct 19 '11 at 08:06

1 Answers1

3

I've always preferred to use different objects for Hibernate/JPA entities and JSF beans, decoupling the differents tiers and having different context for the objects. It avoids also attach/detach problems with ORMs, and let me have a decoupled Service Oriented Arquitecture.

However, if I'd really want to do that with JSF and Hibernate, I'd avoid annotations in the beans:

  • Using Hibernate without annotations, keeping the mapping information in a mapping xml file.
  • Using JSF 2 with a xml file with all information about JSF beans.

So, I hadn't in the classes neither any persistence information nor any JSF information, and I could use the same objects for both tiers.

luchoct
  • 419
  • 3
  • 6