標籤:
// 封裝查詢條件 @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(); }
hibernate封裝查詢,篩選條件然後查詢