Hibernate批量删除的两种方式
Posted 想~(●—●)肥~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate批量删除的两种方式相关的知识,希望对你有一定的参考价值。
第一种:使用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批量删除的两种方式的主要内容,如果未能解决你的问题,请参考以下文章
Java之MyBatis 批量删除数据,两种方式(注解,XML)