Reputation: 9191
All of the code related to this question is in the hyperlinks below.
I want to access a session object in the PetController.java file from the spring petclinic sample application. I have my application configured to use jpa.
Here is what I want to add to one of the methods in PetController.java
:
Session session = entityManager.unwrap(Session.class);
Blob blob = Hibernate.getLobCreator(session).createBlob(file.getInputStream(), file.getSize());
My question is how do I set up the entityManager
so that it is organized centrally and connected to everything in the application to which it needs to be connected?
I found this example of EntityManager in petclinic's JpaVetRepositoryImpl.java. It uses the syntax:
@PersistenceContext
private EntityManager em;
But the EntityManager
does not seem to be called from VetController.java.
I need to call the session
object, and thus likely the entitymanager
, from PetController.java. (For those interested, this is a file coming in from the user through a web form, but I do not want to confuse this posting by making it too complicated. I just want a simple answer to how can I get a session
object in PetController.java
using jpa.) What syntax do I use in PetController.java
? And what other changes do I need to make elsewhere in the application in order for the entityManager
and sessions
to be managed centrally for the entire application?
Upvotes: 0
Views: 858
Reputation: 1246
The reason the code is organized like this in the sample project is because all persistence code would be better suited in the petclinic.model
package which contains the project's DAOs (data access objects) the classes with the xxxRepository
naming convention. The job of the controller is to simply route HTTP requests to business logic and should be kept slim (logic-wise). For your example you might be better off creating a new DAO and service class, maybe called FileService
and FileRepository
, along with their corresponding implementations (you can use existing classes in the sample for examples). Once these classes are created you could include the FileService
in any controllers that needed it. For the PetController
the flow of your logic would look something like this PetController -> FileService -> FileRepository.saveFile()
. If you wanted to centralize the entity manager I would only suggest doing it for a generic DAO class that the other DAOs descend from and not including the entity manager in the controllers.
Upvotes: 1
Reputation: 7449
You should avoid accessing session object directly, and use injected EJB (PetRepository) instead. All your database/jpa business logic must lie inside EJB methods, which are transactional by default.
Upvotes: 1