Hibernate: check if object exists

后端 未结 4 517
广开言路
广开言路 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: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.

提交回复
热议问题