infinikli
infinikli

Reputation: 73

EntityManager lifecycle and persistent client-server-communication

we are developing an (JavaSE-) application which communicates to many clients via persistent tcp-connections. The client connects, performs some/many operations (which are updated to a SQL-Database) and closes the application / disconnects from server. We're using Hibernate-JPA and manage the EntityManager-lifecycle on our own, using a ThreadLocal-variable. Actually we create a new EntityManager-instance on every client-request which works fine so far. Recently we profiled a bit and we found out that hibernate performs a SELECT-query to the DB before every UPDATE-statement. That is because our entities are in detached-state and every new EntityManager attaches the entity to the persistence context first. This leads to a massive SQL-overhead when the server is under load (because we have an write-heavy application)and we try to eliminate that leak.

In short: we are looking for a way to get rid of those SELECT-statements before every UPDATE. Any ideas out there?

Upvotes: 3

Views: 807

Answers (2)

axtavt
axtavt

Reputation: 242786

One possible way to get rid of select statements when reattaching detached entities is to use Hibernate-specific update() operation instead of merge().

update() unconditionally runs an update SQL statement and makes detached object persistent. If persistent object with the same identifier already exists in a session, it throws an exception. Thus, it's a good choice when you are sure that:

  1. Detached object contains modified state that should be saved in the database
  2. Saving that state is the main goal of opening a session for that request (i.e. there were no other operations that loaded entity with the same id in that session)

In JPA 2.0 you can access Hibernate-specific operations as follows:

em.unwrap(Session.class).update(o);

See also:

Upvotes: 2

bpgergo
bpgergo

Reputation: 16057

One possible option would be to use StatelessSession for the update statements. I've successfully used it in my 'write-heavy' application.

Upvotes: 0

Related Questions