Hibernate: check if object exists

后端 未结 4 596
广开言路
广开言路 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: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;
    }
    

提交回复
热议问题