hibernate3 的常用操作(批量删除,批量插入,关联查询)

本文介绍了使用Hibernate进行批量删除、插入及更新的方法,并详细解释了如何通过HQL执行关联查询。此外,还展示了如何利用SQL批量插入数据。

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();

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);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱美事爱生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值