0

I have a spring-jpa-mvc-rest-hibernate web application that I use Java Config almost 99% on the whole app.

How can I configure Session per Request on pure Java Config? Preferable not using hibernate specific code, if that is possible.

I'm using Spring 4.2.2.RELEASE, Spring Data 1.11.0.RELEASE, Spring JPA 1.9.0.RELEASE, Spring WebMVC 4.2.2.RELEASE and Hibernate 5.0.2.Final.

Thanks a lot.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
ElMangau
  • 51
  • 2
  • 6
  • Do you use Spring Security? Spring security allows you to manage sessions. Here is little snippet https://gist.github.com/Mati20041/d293662afa35ccddb143 . – Mati Oct 29 '15 at 22:54
  • By Session per Request I mean Hibernate/JPA Session per Web Request, the one used for database transactions, queries, etc. I'm getting the infamous No Session Exception on Lazy relationships. That was my mistake, I didn't put that clear on my question, sorry, my bad. I use Spring Security with Stateless sessions but that are diferent kind of sessions. – ElMangau Oct 30 '15 at 04:24
  • One thing I forgot to mention is that I'm using JPA EntityManager with TransactionManager (and Hibernate's JPA Vendor Adapter beneath them). – ElMangau Oct 31 '15 at 16:50
  • The simplest advice for now is that you need to do all your operations over your `Entity` within method that is marked with `@Transactional` annotation. This annotation starts transactions. You might get exception on lazy object because you tries to use `Entity` object outside `@Transactional` which makes it detached from session. – Mati Oct 31 '15 at 22:28
  • I'm using @Transactional(readOnly = true) annotation on the REST controller class and @Transactional(readOnly = false) on each method of the class that modifies any data, and I'm doing all the queries and modifications inside those methods. The exception is thrown when I have an Entity A have a reference to a lazy Entity B and I return the Entity A with ResponseEntity, then outside it is taken by jackson and converted to JSON. And there is when I got that Lazy Exception. – ElMangau Nov 02 '15 at 16:37
  • That is why you should not return Entity objects outside your service. Spring is trying to serialize object inside ResponseEntity to ex. JSON with all its fields (also these which are lazy and outside `@Transactional`). You should create some Response object which will return by controller only needed information to client. In controller you get from input Form objects (or some says Command) and return Response objects. Inside `@Transactional` you can create Response and write needed information from Entity. – Mati Nov 03 '15 at 16:59
  • That worked as a charm, thanks a lot. – ElMangau Nov 10 '15 at 20:38

0 Answers0