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

时间:2023-03-08 20:17:25
    // 封装查询条件

    @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(); }