Which pattern to use to open and close hibernate sessions (MyFaces 2.2.2 + Spring 4.0.3 + Hibernate 4.3.2)

StackOverflow https://stackoverflow.com/questions/23127603

Pregunta

I am creating a new project and I have some doubts about the spring + hibernate management. First of all I want to say that I've been reading a lot and I tried to document myself, but after weeks I am still a bit lost on this topic.

Project configuration

  • My architecture follows this structure:

    JSF Beans --> Facade layer --> Service Layer --> DAO Layer

  • My hibernate handles all DAOS and is fully integrated with Spring.

  • The whole Datasource and Hibernate configuration is done in Spring configuration files, so spring manages everything.
  • I use Spring Security to handle the project security.

Everything seems to be well integrated but I still can't find a solid solution to manage Hibernate Sessions.

My first approach was to use OSIV using JSF PhaseListeners, but then I integrated Spring and started using @Transactional annotations on my Service layer.

Here are my questions:

  • I think everytime @Transactional method is invoked an Hibernate session is opened and closed right? Or am I wrong?

  • With @Transactional I am sure I am going to run in trouble because Hibernate's Lazy instantiation on the Render response phase, and I don't want to do EAGER fetch. So ...

  • Is it safe to use OSIV? Or is it really vulnerable to DOS attacks?

  • Is there a better way to handle Lazy fetching problem than OSIV pattern? I am sure I am missing better patterns, can you throw a little bit of light to the topic?

I didn't post any code because all my questions are basically conceptual on architecture, but if you need any of my code to understand me (I know I am a mess explaining myself), you just have to ask me and I'll post it as soon as I can.

Thank you all!

¿Fue útil?

Solución

That is a LOT of questions, I wouldn't expect anyone to answer all of them fully in one go. I'll give my best on questions 1 and 2:

1) When a method with @Transactional is invoked on a bean (i.e. not directly in the same class), Spring checks for an existing transaction and does something. That something is set by your configuration (and may be configured differently for methods or beans), see Transaction Propagation. So you could be using an existing one, making a new one or not using a transaction at all.

2) I found non-eager fetching to be a problem in my projects. It certainly is possible, but IMHO it's difficult to maintain and adds extra space for a mistake. This problem has been discussed before (answer is again: possible, but requires extra work, you should weight the benefits vs effort for your specific situation): Open Session In View Pattern

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top