Hibernate: check if object exists

后端 未结 4 518
广开言路
广开言路 2021-01-01 10:06

Suppose, objects of type A are stored in DB. Here\'s the way I load specific one from DB using hibernate:

org.hibernate.Session session = ...;
long id         


        
相关标签:
4条回答
  • 2021-01-01 10:39

    Hibernate

    Fetches only key for optimal performance:

    public boolean exists(Class clazz, String idKey, Object idValue) {
        return getSession().createCriteria(clazz)
                .add(Restrictions.eq(idKey, idValue))
                .setProjection(Projections.property(idKey))
                .uniqueResult() != null;
    }
    

    JPA

    Since Hibernate is an implementation of JPA, it is possible to inject an EntityManager. This method also has good performance because it lazily fetches the instance:

    public boolean exists(Class clazz, Object key) {
       try {
          return entitymanager.getReference(Entity.class, key) != null;
       } catch (EntityNotFoundException.class) {
          return false;
       }
    }
    
    0 讨论(0)
  • 2021-01-01 10:40

    A bit simplified method of @Journeycorner

    public boolean exists(Class<?> clazz, Object idValue) {
        return getSession().createCriteria(clazz)
                .add(Restrictions.idEq(idValue))
                .setProjection(Projections.id())
                .uniqueResult() != null;
    }
    

    A below method can be useful also. Keep in mind, that this method can be used only with the criteria that can produce not more than one record (like Restrictions.idEq() criteria)

    public static boolean uniqueExists(Criteria uniqueCriteria) {
        uniqueCriteria.setProjection(Projections.id());
        return uniqueCriteria.uniqueResult() != null;
    }
    
    0 讨论(0)
  • 2021-01-01 10:41

    You can use session.get:

    public Object get(Class clazz,
                      Serializable id)
               throws HibernateException
    

    It will return null if the object does not exist in the database. You can find more information in Hibernate API Documentation.

    0 讨论(0)
  • 2021-01-01 10:49

    you can use HQL for checking object existence:

    public Boolean exists (DTOAny instance) {
        Query query = getSession().             
        createQuery("select 1 from DTOAny t where t.key = :key");
            query.setString("key", instance.getKey() );
        return (query.uniqueResult() != null);
    }
    

    Hibernates uniqueResult() method returns null if no data was found. By using HQL you can create more complex query criterium.

    0 讨论(0)
提交回复
热议问题