Hibernate框架HQL语句动态条件查询

HQL语句动态条件查询可以根据条件是否存在自动封装hql语句的查询条件,在这里使用map集合来实现,也可以通过创建实体条件类来创建,但是创建类太多,如果使用该查询频率较高可以使用这种方法,实体类方法与map方法类似
其中自定义的条件名要与map键值对的key值相同,每一个and前要预留空格,否则会报org.hibernate.hql.ast.QuerySyntaxException异常

public static void zuhetiaojianchaxunformap(){
		Session session = HibernateUtil.getSession();
		Map<String, Object> map = new HashMap<>();
		map.put("hnianling", 25);
		map.put("lnianling", 22);
		map.put("xingbie", 1);
		map.put("xingming", "张三");
		StringBuffer s = new StringBuffer();
		s.append(" from Xuesheng where 1=1 ");
		if (map.get("hnianling")!=null){
			s.append(" and nianling<=:hnianling");
		}
		if(map.get("lnianling")!=null){
			s.append(" and nianling>=:lnianling");
		}
		if(map.get("xingbie")!=null){
			s.append(" and xingbie=:xingbie");
		}
		if(map.get("xingming")!=null){
			s.append(" and xingming=:xingming");
		}
	
		Query query = session.createQuery(s.toString());
		query.setProperties(map);
		List<Xuesheng> list = query.list();
		for (Xuesheng xuesheng : list) {
			System.out.println("姓名:"+xuesheng.getXingming()+",年龄:"+xuesheng.getNianling());
		}
	}

map里有几个条件sql语句中就会添加几个,生成的sql语句如下:

 select
        xuesheng0_.xuehao as xuehao0_,
        xuesheng0_.xingming as xingming0_,
        xuesheng0_.xingbie as xingbie0_,
        xuesheng0_.nianling as nianling0_ 
    from
        xueshengbiao xuesheng0_ 
    where
        1=1 
        and xuesheng0_.nianling<=? 
        and xuesheng0_.nianling>=? 
        and xuesheng0_.xingbie=? 
        and xuesheng0_.xingming=?

你可能感兴趣的:(Hibernate框架)