Spring data jpa批量插入和更新


publicinterface BatchDao<T> {
    publicvoid batchInsert(List<T> list);
     
    publicvoid batchUpdate(List<T> list);
}

publicinterface ReceiptDao extendsPagingAndSortingRepository<Receipt, Long>, BatchDao<Receipt> {
     
    // start回单录入
    Page<Receipt> findByUserId(Long userId, Pageable pageable);
 
}

importjava.util.List;
 
importjavax.persistence.EntityManager;
importjavax.persistence.PersistenceContext;
 
importorg.hibernate.Query;
importorg.hibernate.ScrollableResults;
importorg.hibernate.Session;
importorg.springframework.transaction.annotation.Transactional;
 
importcom.ygsoft.cxpt.dao.BatchDao;
importcom.ygsoft.util.dwz.Page;
 
/**
 *
 * @author <a href="mailto:[email protected]">ketayao</a> Version 1.1.0
 * @since 2012-8-27 上午10:55:41
 */
 
publicabstract class AbstractDao implementsBatchDao{
 
    @PersistenceContext
    protectedEntityManager em;
 
    @Transactional
    publicvoid batchInsert(List list) {
        for(inti = 0; i < list.size(); i++) {
            em.persist(list.get(i));
            if(i % 30== 0) {
                em.flush();
                em.clear();
            }
        }
    }
     
    @Transactional
    publicvoid batchUpdate(List list) {
        for(inti = 0; i < list.size(); i++) {
            em.merge(list.get(i));
            if(i % 30== 0) {
                em.flush();
                em.clear();
            }
        }
    }
 
    /**
     * Hibernate使用游标分页的一个通用查询分页方法
     * 描述
     * @param queryString
     * @param parameters
     * @param page
     * @return
     */
    @SuppressWarnings("unchecked")
    publicList findPageByQuery(finalString queryString,
            finalObject[] parameters, finalPage page) {
 
        Session session = (Session) em.getDelegate();
 
        Query query = session.createQuery(queryString);
 
        // 判断有无条件参数的情况
        if(parameters != null) {
            for(inti = 0; i < parameters.length; i++) {
                query.setParameter(i, parameters[i]);
            }
        }
 
        // 使用游标来得到总条数
        ScrollableResults sr = query.scroll();
        sr.last();
        inttotalCount = sr.getRowNumber();
 
        // 索引加1
        inttotalRec = totalCount + 1;
        page.setTotalCount(totalRec);
 
        intstartIndex = (page.getPageNum() - 1) * page.getNumPerPage();
 
        query.setFirstResult(startIndex);
        query.setMaxResults(page.getNumPerPage());
 
        List reList = query.list();
 
        returnreList;
    }
}

importcom.ygsoft.cxpt.entity.FmisItem;
 
/**
 * 
 * @author  <a href="mailto:[email protected]">ketayao</a>
 * Version  1.1.0
 * @since   2012-9-7 下午5:28:58 
 */
@Repository
publicclass FmisItemDaoImpl extendsAbstractDao<FmisItem> {
 
}


你可能感兴趣的:(Spring data jpa批量插入和更新)