前言
此處以一個Student案例進行演示 根據Student的ids進行批量查詢和刪除
1.批量查詢
1.1 批量查詢Dao層代碼
public List<Student> excuteBatchQuery(String sql, Map<String, List<Object>> map) {
Session session = this.getSessionFactory().getCurrentSession();
SQLQuery query = session.createSQLQuery(sql).addEntity(Student.class);
if (map != null && map.size() > 0) {
for (Map.Entry<String, List<Object>> entry : map.entrySet()) {
query.setParameterList(entry.getKey(), entry.getValue());
}
}
return query.list();
}
1.2 批量查詢Service層代碼
@Transactional(rollbackFor = Throwable.class)
public List<Student> batchQuery(String ids) {
String sql = "select * from T_STUDENT where STUDENT_ID in (:id)";
Map<String, List<Object>> map = new HashMap<>();
List<Object> idLong = new ArrayList<>();
for (Object id : CollectionUtils.arrayToList(ids.split(","))) {
idLong.add(Long.parseLong(id.toString()));
}
map.put("id", idLong);
return studentDao.excuteBatchQuery(sql, map);
}
2.批量刪除
2.1 批量刪除Dao層代碼
public void excuteBatchDelete(String sql, Map<String, List<Object>> map) {
Session session = this.getSessionFactory().getCurrentSession();
SQLQuery query = session.createSQLQuery(sql);
if (map != null && map.size() > 0) {
for (Map.Entry<String, List<Object>> entry : map.entrySet()) {
query.setParameterList(entry.getKey(), entry.getValue());
}
}
query.executeUpdate();
}
2.2 批量刪除Service層代碼
@Transactional(rollbackFor = Throwable.class)
public void batchDelete(String ids) {
String sql = "delete from T_STUDENT where STUDENT_ID in(:id)";
Map<String, List<Object>> map = new HashMap<>();
List<Object> idLong = new ArrayList<>();
for (Object id : CollectionUtils.arrayToList(ids.split(","))) {
idLong.add(Long.parseLong(id.toString()));
}
map.put("id", idLong);
this.studentDao.excuteBatchDelete(sql, map);
}
注意:
1.Dao層需要繼承HibernateGenericDao接口
2.在Service層必須開啓事務 否則會出錯(@Transactional)