hibernate3 的常用操作(批量刪除,批量插入,關聯查詢)

xmnx 9年前發布 | 7K 次閱讀 Java Hibernate3

1 批量刪除是調用sql引擎執行sql語句。批量插入有兩種方式,a:自己拼接出一條sql語句 b:利用hibernate的session一級緩存,每多少條刷新緩存存入數據庫

@Component
public class StudentDao extends HibernateDao<Student, Integer> {

public void deleteByIds(List<?> ids) {
    String hql = "delete from Student where id in (:ids)";
    createQuery(hql).setParameterList("ids", ids).executeUpdate();
}

public void saveBatch(List<Student> stuList) {
    if (null != stuList && stuList.size() > 0) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try {
            for (int i = 0; i < stuList.size(); i++) {
                session.save(stuList.get(i));
                if (i % 100 == 0) { // 每一百條刷新并寫入數據庫
                    session.flush();
                    session.clear();
                }
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        }finally{
            tx.commit();
            session.close();
        }
    }
}

} //批量查詢,當然hibernate也提供了使用某一個屬性查詢出集合 String hql = "from Goods where merchandiseId in (:ids)"; List<Goods> goodsList = goodsDao.createQuery(hql).setParameterList("ids", idList).list();</pre>

2 批量插入采用sql時如下:

public void setMappingGoods(Integer merchandiseId,List<Integer> ids) {
        StringBuilder sb = new StringBuilder();
        sb.append("insert into mapping_goods(kid,oid) values ");
        for(Integer id:ids){
            sb.append("("+merchandiseId+","+id+")"+",");
        }
        goodsmapDao.getSession().createSQLQuery(sb.substring(0, sb.length()-1)).executeUpdate();
    }

3 hql 關聯查詢:當沒有在實體中設置關聯關系,而是自己建立的中間表時,可以用hql關聯查詢數據。

    public List<Goods> getMappingGoods(String kuuid) {
        if(StringUtils.empty(kuuid)){
            return new ArrayList<Goods>();
        }
        String hql = " from Goods g where  g.merchandiseUuid!=? and ( (g.merchandiseUuid in (select mp.kuuid from Goodsmap mp where mp.kuuid=? or mp.ouuid=?)) or (g.merchandiseUuid in (select mp.ouuid from Goodsmap mp where mp.kuuid=? or mp.ouuid=?)))";
        return goodsDao.find(hql,kuuid, kuuid,kuuid, kuuid,kuuid);
    }

 本文由用戶 xmnx 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!