1. 程式人生 > >Hibernate批量刪除的兩種方式

Hibernate批量刪除的兩種方式

true ide inf try from tracking 批量刪除 query 個數

第一種:使用Hibernate映射類對對象進行封裝操作

---------------------------------------------------------------------------

@Override
public boolean deleteTrainee(long[] id) {
try {
Session session = HibernateSessionFactory.getSession();
Transaction ts = session.beginTransaction();

//采用hibernate映射類的方法進行刪除
for (long idList: id) {
Trainee t = (Trainee)session.load(Trainee.class, idList);
if (t != null)
session.delete(t);
}
ts.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
HibernateSessionFactory.closeSession();
}
}

---------------------------------------------------------------------------

第二種:采用hql語句,拼接字符串設置占位符的方式進行操作

---------------------------------------------------------------------------

@Override
public boolean deleteSupportTracking(Long[] id) {
try {
Session session = HibernateSessionFactory.getSession();
Transaction ts = session.beginTransaction();

//設定占位符的個數
String sql = "";
for (int i = 0; i < id.length; i++) {
if (i == 0) {
sql = sql + "?";
} else {
sql = sql + "," + "?";
}
}
Query Query = session.createQuery("DELETE FROM SupportTracking WHERE id in(" + sql + ")");
//設置占位符中的參數
Long[] ints = new Long[id.length];
for(int i=0; i<id.length; i++){
ints[i] = id[i];
Query.setParameter(i, ints[i]);
}
int k = Query.executeUpdate();
ts.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
HibernateSessionFactory.closeSession();
}
}

---------------------------------------------------------------------------

2.1網上抄來的寫法,未測試(先放這,有空再試試)

---------------------------------------------------------------------------

public void deletes(List<Integer> idList) {
String hql = "";
for (int i = 0; i < idList.size(); i++) {
if(i==0) {
hql = "id="+idList.get(i);
} else {
hql =hql + " or id="+idList.get(i);
}
Session session= this.getSession();
Query q= session.createQuery("delete from Timeliftinfo where "+hql);
q.executeUpdate();
}

}

---------------------------------------------------------------------------

Hibernate批量刪除的兩種方式