Search code examples
javaperformancejpajdbcpersistent

When does JPA's EntityManager give Performance Benefits over plain JDBC?


I am working on a database application for a client. The old application code is quite inconsistent in how it accesses the database; in some methods it's using Hibernate objects, in others it creates JDBC connections directly and uses pure SQL, in some it creates Hibernate connections and uses those to get the JDBC connection. In any case, we're going to overhaul a lot of code to make it consistent. Our client has heard of JPA, and asked us to use it, because the client believes it will come with a performance benefit.

The problem is, my understanding of the performance benefits from JPA is that the big benefit comes from JPA's EntityManager, because it allows you to persist objects in-memory between database calls. However, the application we're working on won't be the only application accessing the database, and will run in multiple instances at multiple locations. In addition, EntityManagers aren't thread-safe so we wouldn't even be able to see changed data in a different part of the same application. As such, it looks like we would need to get a new EntityManager from the EntityManagerFactory in each method, and close it when the method is complete. Thus, we wouldn't really be able to persist objects in-memory very long, because other applications would need the data we change & change the data we need.

The current code is such a mess that moving to JPA would give major benefits in maintainability and consistency anyways. However, if it won't provide performance benefits, we should let the client know as soon as possible so they're not disappointed. Are there other ways that JPA provides performance benefits besides the obvious one related to Persistance Contexts?

I've checked other questions on StackOverflow, but the ones I've found talk about changes in large batches (example here). Our client wants the changes made by one application to be visible to other applications as soon as possible, so our application will make several small changes, rather than occasional batch changes.

Thank you.


Solution

  • JPA will not necessarily give you any performance advantage over plain JDBC. It might have big imapcts on your system. It all depends on how you use it.

    It sounds like you are using Hibernate already. JPA itself is a specification, which is implemented by a number of vendors or providers. Hibernate is one of them (and is the JPA2 provider that I use at work).

    Creating an EntityManagerFactory can take some time. Creating an EntityManger, on the other hand, is fast and lightweight.

    If you are experiencing poor performance, you might try profiling the code to see where the performance issues lie.

    Moving to a single access layer sounds like a good idea to me, though, and it does improve maintainability and consistency.