您的位置:首页 > 其它

hibernate封装查询,筛选条件然后查询

2015-09-15 23:22 489 查看
// 封装查询条件

@Test
public void transmitParameter() {
Map map = new HashMap<String, String>();
// map.put("sid", "1");
map.put("s_name", "");
test1(Student.class, map);
// 可能会根据筛选来查询!有的条件可能值为空
}

public void test1(Class classs, Map<String, String> p) {
Session session = startCfg.getSession();
Transaction t = session.beginTransaction();
// 拼接sql语句
StringBuffer sb = new StringBuffer();
sb.append("from "
+ session.getSessionFactory().getClassMetadata(classs)
.getEntityName() + " where 1=1 ");
// 搜索哪些字段要根据map来添加
for (Entry<String, String> entry : p.entrySet()) {
if (!entry.getValue().equals("")) {
sb.append(" and " + entry.getKey() + "=:" + entry.getKey());
}
}

Query query = session.createQuery(sb.toString());
for (Entry<String, String> entry : p.entrySet()) {
if (!entry.getValue().equals("")) {
query.setParameter(entry.getKey(), entry.getValue());
}
}
List list = query.list();
System.out.println(list.toString());
t.commit();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: