Hibernate session.contains (Class clazz, Serializable id)

I want to check if a session contains an entity of a given class / identifier. I do not see a way to do this at the moment.

  • contains() accepts an object of an object not class + key
  • get() queries the database if the object is missing, which I do not want to do
  • load() never returns null since the proxy is always created, so I cannot use this method

Is it possible to do the above without side effects / database queries?

+6
source share
5 answers

Answering my own question.

I do not think this is possible with public APIs. However, if you are willing to endure some cheeses, you can do the following

  SessionImplementor sessionImplementor = ((SessionImplementor)session); EntityPersister entityPersister = sessionImplementor.getFactory().getEntityPersister( clazz.getName() ); PersistenceContext persistenceContext = sessionImplementor.getPersistenceContext(); EntityKey entityKey = new EntityKey( id, entityPersister, EntityMode.POJO ); Object entity = persistenceContext.getEntity( entityKey ); if ( entity != null ) return entity; entity = persistenceContext.getProxy( entityKey ); if ( entity != null ) return entity; return null; 

This depends on the internal hibernation APIs, so it may not work in the future if it changes internally.

+1
source

It works:

 public boolean isIdLoaded(Serializable id) { for (Object key : getSession().getStatistics().getEntityKeys()) { if (((EntityKey) key).getIdentifier().equals(id)) { return true; } } return false; } 
+4
source

Not that I knew. A session always checks the database if you are trying to get an entity of a certain type and identifier, and it does not contain it.

This is actually one of the good things about the model. You do not need to worry about where the JPA / Hibernate gets the object, cache (1st or 2nd level) or DB.

If you have an entity in memory, you can check to see if it is detached from the session, but not if it is in the session.

+1
source

Use getIdentifier(..) . It returns the value of the identifier of this object associated with the current session, see Javadoc .

0
source
 public static boolean sessionContains(Session session, Class<?> aClass, Serializable id) { return Hibernate.isInitialized(session.load(aClass, id)); } 

session#load() does not go to the database and always returns Object. If the return value is Proxy, then the session does not contain the passed id / class pair. Otherwise, the session already has this object.

0
source

Source: https://habr.com/ru/post/897622/


All Articles