I am working on an older desktop application (Swing) that communicates directly with an SQL database.
So far, the data communication is done directly using JDBC. Partly DAOs are used that supply POJOs with data and store the POJOs in the database. In other parts of the application, resultsets are used directly.
The application is mostly CRUD operations. What is the best design pattern to follow in such an application if you want to use JPA in newer parts of the application?
The POJOs for the newer parts will become entities or DTOs that map a subset of the entities. If you can use entities (lazy loading is no concern and no need for data aggregation), you just write your query (or if you simply want a by id query use EntityManager.find) and return the result to your representation layer. There is nothing special for the querying part. You can just omit the manual mapping of JDBC result sets to objects as Hibernate will take care of that for you.
For the write part, things are a bit more “complicated”. I suppose your transaction model is just on the DAO layer? If so, you can use EntityManager.getTransaction().begin() and EntityManager.getTransaction().commit() in there and to flush entities that you pass in, you can use EntityManager.merge. I would recommend you to read into the entity state lifecycle though to understand what is happening.
For the query-part: Would you detach the entities from the hibernate session just after reading them? Btw: Does a read only hibernate session automatically produce detached entities?
I personally would use DTOs with Blaze-Persistence Entity-Views which handles all the mappings for you, but if you don’t want to add a library, then yes, detach the entities after read. A stateless session in fact does the detaching automatically.