加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:31:29 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 1 批量删除是调用sql引擎执行sql语句。批量插入有两种方式,a:自己拼接出一条sql语句 b:利用hibernate的session一级缓存,每多少条刷新缓存存入数据

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

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

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

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

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读