Hibernate session.contains(Class clazz,Serializable id) [英] Hibernate session.contains( Class clazz, Serializable id )

查看:263
本文介绍了Hibernate session.contains(Class clazz,Serializable id)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够检查会话是否包含给定类/标识符的实体。

I want to be able to check whether a session contains an entity of a given class/identifier. I can't see a way to do this at the moment.


  • contains()接受一个实体对象而不是class + key
  • get()查询数据库,如果实体不存在, t想做

  • load()永远不会返回null,因为代理总是被创建的,所以我不能使用这个方法
  • li>
  • contains() takes an entity object not class + key
  • get() queries the database if the entity is not present which I don't want to do
  • load() never returns null as a proxy is always created so I can't use this method

有没有可能对DB做任何副作用/查询?

Is it possible to do the above with no side-effects/queries to DB?

推荐答案

回答我自己的问题。

我不相信这对公共API是可能的。然而,如果你愿意容忍一些奶酪,你可以执行以下操作:

I do not believe this is possible with the public APIs. However if you are willing to tolerate some cheese 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;

这依赖于hibernate的内部API,因此如果内部发生更改,将来可能无法工作。

This relies on internal APIs of hibernate so may not work in future if it changes internally.

这篇关于Hibernate session.contains(Class clazz,Serializable id)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆