在Hibernate中创建动态sql;我如何实现1 = 1 [英] In Hibernate while creating dynamic sql; how do i implement 1=1
问题描述
我正在使用hibernate。我需要在下面创建查询。在这种情况下,subContest可能为null,在这种情况下, subContest_id = subContest_id;
但是如何在下面的情况下实现它。这里如果我试图 query.setParameter(cont,subContest_id);
它会给出异常,因为cont应该是一个id而不是一个字符串。 p>
I am using hibernate. I need to create query below. It is possible the subContest is null in which case subContest_id=:cont
should NOT be part of where clause. In conventional SQL when creating dynamic sql ; for such cases I used to do subContest_id = subContest_id ;
BUT how do I achieve it in case below. Here If I try to query.setParameter( "cont", "subContest_id " );
it will give exception as cont is supposed to be an id and not a string.
Query query = getEntityManager().createQuery( "select * from Upload where moderated=:mod, subContest_id=:cont order by lastModifiedTime desc " );
query.setParameter( "cont", subContest.getId() );
推荐答案
您可以尝试在hibernate中使用条件查询
you can try using criteria query in hibernate
Criteria criteria = session.createCriteria(Upload.class);
您可以添加您的where子句作为限制
you can add your where clause as restrictions
Criteria criteria = session.createCriteria(Upload.class)
.add(Restrictions.eq("mode", value));
在您的情况下,您希望在添加限制之前检查为空。
in your case you want to check null before adding restriction
if(subContest_id!=null){
criteria.add(Expression.le("subContest_id",subContest_id));
}
并且最后可以使用这个命令完成
and finally order by can be done using this
Criteria criteria = session.createCriteria(Upload.class)
.addOrder( Order.desc("lastModifiedTime") );
请参考 here ,了解如何使用条件查询的详细信息。
please refer here for details on how to use criteria queries
这篇关于在Hibernate中创建动态sql;我如何实现1 = 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!