Hibernate 批量删除 批量 插入 关联查询
2016-12-17 18:47
387 查看
@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); }
相关文章推荐
- 第十六周项目3-归并排序算法的排序
- 选手及评委素材信息规范处理说明
- 杰瑞教育Android项目实训整理
- httpclient SocketTimeout ConnectTimeout ConnectionRequestTimeout
- 麻辣烫与安卓主线程工作原理
- 静态顺序表的基本操作
- 如何修改codeblocks主题
- java网络编程(四)
- QHash
- eclipse插件
- POJ 2112 Optimal Milking 已翻译
- Servlet,GenericServlet,HttpServlet源码解析
- Java Web开发过程用各种代码的注释
- monkeyrunner脚本的编写、运行和常用api简介
- Netty学习四:Channel
- Tomcat之使用方式
- java(多线程)
- C语言打印short、long、long long和unsigned类型整数
- 【iOS开发】即时视频聊天实现
- QMap