hibernate3 的常用操作(批量删除,批量插入,关联查询)
2015-02-09 17:37
211 查看
1 批量删除是调用sql引擎执行sql语句。批量插入有两种方式,a:自己拼接出一条sql语句 b:利用hibernate的session一级缓存,每多少条刷新缓存存入数据库
2 批量插入采用sql时如下:
3 hql 关联查询:当没有在实体中设置关联关系,而是自己建立的中间表时,可以用hql关联查询数据。
@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); }
相关文章推荐
- hibernate3 的常用操作(批量删除,批量插入,关联查询) (未测试)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- MongoDB常用命令汇总之插入、更新和删除操作详解。
- 使用“一条”SQL语句完成批量插入和批量删除操作
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- mybatis 操作(批量插入,批量修改,批量删除, 分页查询)
- Spring JDBC 常用批量操作及插入操作
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- 单链表的常用操作,包括单链表的创建、插入、删除、排序、逆置以及打印输出等
- Spring JDBC 常用批量操作及插入操作
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate批处理操作优化 (批量插入、更新与删除)
- Hibernate 批量删除 批量 插入 关联查询