Example usage for org.hibernate Query setMaxResults

List of usage examples for org.hibernate Query setMaxResults

Introduction

In this page you can find the example usage for org.hibernate Query setMaxResults.

Prototype

@Override
    Query<R> setMaxResults(int maxResult);

Source Link

Usage

From source file:com.dell.asm.asmcore.asmmanager.db.TemplateDAO.java

License:Open Source License

public TemplateEntity getTemplateById(String Id) {

    Session session = null;//from ww  w .j  a va 2  s. com
    Transaction tx = null;
    TemplateEntity templateEntity = null;

    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        // Create and execute command.
        String hql = "from TemplateEntity where template_id =:id";
        Query query = session.createQuery(hql);
        query.setString("id", Id);
        templateEntity = (TemplateEntity) query.setMaxResults(1).uniqueResult();

        // Commit transaction.
        tx.commit();

    } catch (Exception e) {
        logger.warn("Caught exception during get template for template id: " + Id + ", " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during get template: " + ex);
        }
        throw new AsmManagerInternalErrorException("Retrieve Template by Id", "TemplateDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during get template: " + ex);
        }
    }

    return templateEntity;
}

From source file:com.dell.asm.asmcore.asmmanager.db.TemplateDAO.java

License:Open Source License

public TemplateEntity updateTemplate(TemplateEntity updatedTemplate) throws AsmManagerInternalErrorException {
    Session session = null;/* w ww  .ja  va  2 s  .  co m*/
    Transaction tx = null;
    TemplateEntity templateEntity = null;

    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();
        String hql = "from TemplateEntity where template_id = :id";
        Query query = session.createQuery(hql);
        query.setString("id", updatedTemplate.getTemplateId());
        templateEntity = (TemplateEntity) query.setMaxResults(1).uniqueResult();

        if (templateEntity != null) {
            templateEntity.setTemplateType(updatedTemplate.getTemplateType());
            templateEntity.setTemplateDesc(updatedTemplate.getTemplateDesc());
            // templateEntity.setDisplayName(updatedTemplate.getDisplayName());
            // templateEntity.setDeviceType(updatedTemplate.getDeviceType());
            templateEntity.setState(updatedTemplate.getState());
            templateEntity.setName(updatedTemplate.getName());
            templateEntity.setUpdatedBy(_dao.extractUserFromRequest());

            //TODO remove the set updated date when @PreUpdate is working
            GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
            templateEntity.setUpdatedDate(now);

            templateEntity.setMarshalledTemplateData(updatedTemplate.getMarshalledTemplateData());
            session.saveOrUpdate(templateEntity);

            //commit
            tx.commit();
        } else {
            String msg = "unable to update template with name " + updatedTemplate.getName();
            logger.warn(msg);
        }

    } catch (Exception e) {
        logger.warn("Caught exception during update template: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during update template: " + ex);
        }
        // TODO: Reviewer: instanceof will always return false since a RuntimeException can't be a com.dell.asm.asmcore.asmmanager.exception.AsmManagerCheckedException
        //if (e instanceof AsmManagerCheckedException) {
        //    throw e;
        //}
        throw new AsmManagerInternalErrorException("update Template", "TemplateDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during update template: " + ex);
        }
    }

    return templateEntity;

}

From source file:com.dell.asm.asmcore.asmmanager.db.TemplateDAO.java

License:Open Source License

public void deleteTemplate(String id) {

    logger.info("Deleting template Id : " + id);
    Session session = null;/*from w  ww . j a v a2 s.c  o m*/
    Transaction tx = null;

    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();
        String hql = "from TemplateEntity where template_id =:id";
        Query query = session.createQuery(hql);
        query.setString("id", id);
        TemplateEntity template = (TemplateEntity) query.setMaxResults(1).uniqueResult();

        if (template != null) {
            session.delete(template);
        }
        // Commit transaction.
        tx.commit();
    } catch (Exception e) {
        logger.warn("Caught exception during delete template: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during delete template: " + ex);
        }
        throw new AsmManagerInternalErrorException("Delete Template", "TemplateDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during delete template: " + ex);
        }
    }
}

From source file:com.demo.impl.RecordatoriosImpl.java

@Override
public Recordatorios obtenerProxRecordatorio(Date fecha, int clvGestor) {
    try {//from w  w w.j a  va2s. c  o  m
        Date hoy = new Date();
        Date hoymasCinco = new Date(hoy.getTime() + (5 * 60 * 1000));
        Session s = HibernateUtil.getSessionFactory().openSession();
        Transaction t = s.beginTransaction();

        Query q = s.createQuery("from Recordatorios r where r.recordatorioFecha between :fromdate and :todate "
                + "and r.catGestores.catGestorClv=" + clvGestor + " and r.mostrado='false'");
        q.setMaxResults(1);
        q.setParameter("fromdate", hoy);
        q.setParameter("todate", hoymasCinco);
        Recordatorios r = (Recordatorios) q.uniqueResult();
        t.commit();
        return r;
    } catch (HibernateException exception) {
        LogSistema.guardarlog(this.getClass().getName() + " Method: obtenerProxRecordatorio, Exception: "
                + exception.getMessage());
        return null;
    }
}

From source file:com.dungnv.vfw5.base.dao.BaseFWDAOImpl.java

License:Open Source License

public List<T> find(String boName, List<ConditionBean> lstCondition, String order, int start, int maxResult,
        String logic) {/*from  w  ww  .j  a v  a2s. c  o m*/
    //        if (logic == null) {
    //            logic = ParamUtils.LOGIC_AND;
    //        }
    try {
        StringBuilder sql = new StringBuilder();
        sql.append(" from ");
        sql.append(boName);
        sql.append(" where 1=1 ");
        if (lstCondition != null && !lstCondition.isEmpty()) {
            buildConditionQuery(sql, lstCondition);
        }
        if (order != null && !order.equals("")) {
            sql.append(" order by ");
            sql.append(order);
        }
        Query query = getSession().createQuery(sql.toString());
        if (maxResult != 0) {
            query.setFirstResult(start);
            query.setMaxResults(maxResult);
        }
        fillConditionQuery(query, lstCondition);
        return query.list();
    } catch (HibernateException he) {
        log.error(he.getMessage(), he);
        return null;
    }
}

From source file:com.dungnv.vfw5.base.dao.BaseFWDAOImpl.java

License:Open Source License

public List<T> findSession(String boName, List<ConditionBean> lstCondition, String order, int start,
        int maxResult, String logic, Session session) {
    //        if (logic == null) {
    //            logic = ParamUtils.LOGIC_AND;
    //        }//from   w  ww  .  ja v a2s  .  c om
    try {
        StringBuilder sql = new StringBuilder();
        sql.append(" from ");
        sql.append(boName);
        sql.append(" where 1=1 ");
        if (lstCondition != null && !lstCondition.isEmpty()) {
            buildConditionQuery(sql, lstCondition);
        }
        if (order != null && !order.equals("")) {
            sql.append(" order by ");
            sql.append(order);
        }
        Query query = session.createQuery(sql.toString());
        if (maxResult != 0) {
            query.setFirstResult(start);
            query.setMaxResults(maxResult);
        }
        fillConditionQuery(query, lstCondition);
        return query.list();
    } catch (HibernateException he) {
        log.error(he.getMessage(), he);
        return null;
    }
}

From source file:com.dz.module.charge.ChargeAction.java

public void rollbackImport() throws IOException {
    ServletActionContext.getResponse().setContentType("text/plain");
    ServletActionContext.getResponse().setCharacterEncoding("utf-8");
    PrintWriter out = ServletActionContext.getResponse().getWriter();

    JSONArray jarray = JSONArray.fromObject(jsonStr);

    Session session = HibernateSessionFactory.getSession();
    Transaction tx = null;/* w ww .j  a  va 2s.  c  om*/
    String msg = "???";
    int fid = 0;
    try {
        tx = session.beginTransaction();
        for (int i = 0; i < jarray.size(); i++) {
            int id = Integer.parseInt(jarray.get(i).toString());
            BankRecordTmp bt = (BankRecordTmp) session.get(BankRecordTmp.class, id);
            String licenseNum = bt.getLicenseNum();
            fid = bt.getFid();
            Query q_v = session.createQuery("select carframeNum from Vehicle where licenseNum=:carnum");
            q_v.setString("carnum", licenseNum);
            q_v.setMaxResults(1);
            String carframeNum = q_v.uniqueResult().toString();
            Query q_dept = session.createQuery("select branchFirm from Contract where carframeNum=:id ");
            q_dept.setString("id", carframeNum);
            q_dept.setMaxResults(1);
            String dept = q_dept.uniqueResult().toString();
            Query query = session.createQuery("from ClearTime where department = :dept");
            query.setString("dept", dept);
            Object obj = query.uniqueResult();
            ClearTime ct = (ClearTime) obj;
            Date current = ct.getCurrent();
            if (isYearAndMonth(current, bt.getInTime())) {
                Query q_c = session
                        .createQuery("delete from ChargePlan where feeType='add_bank' and comment=:id");
                q_c.setString("id", "" + id);
                q_c.executeUpdate();
                session.delete(bt);
            } else {
                msg = "???";
            }
        }

        Query q_f = session.createQuery("select count(*) from BankRecordTmp where fid=:id ");
        q_f.setInteger("id", fid);
        long ct = (long) q_f.uniqueResult();
        if (ct == 0) {
            BankFile bf = (BankFile) session.get(BankFile.class, fid);
            session.delete(bf);
        }
        tx.commit();
    } catch (HibernateException ex) {
        ex.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
        msg = "?" + ex.getMessage();
    } finally {
        HibernateSessionFactory.closeSession();
    }

    out.print(msg);

    out.flush();
    out.close();
}

From source file:com.dz.module.contract.BankCardAction.java

public String searchCard() {
    int currentPage = 0;
    if (request.getParameter("currentPage") != null && !(request.getParameter("currentPage")).isEmpty()) {
        currentPage = Integer.parseInt(request.getParameter("currentPage"));

        System.out.println(request.getParameter("currentPage"));
    } else {//from  ww w . ja  v  a  2  s  . c  o m
        currentPage = 1;
    }

    if (bankCard == null) {
        bankCard = new BankCard();
    }

    String hql = "from BankCard where 1=1 ";

    if (!StringUtils.isEmpty(dept) && !dept.startsWith("all")) {
        hql += String.format("and carNum in (select licenseNum from Vehicle where dept='%s') ", dept);
    }

    if (!StringUtils.isEmpty(bankCard.getIdNumber())) {
        hql += String.format("and idNumber like '%%%s%%' ", bankCard.getIdNumber());
    }

    if (!StringUtils.isEmpty(bankCard.getCardNumber())) {
        hql += String.format("and cardNumber like '%%%s%%' ", bankCard.getCardNumber());
    }

    if (!StringUtils.isEmpty(bankCard.getCarNum())) {
        hql += String.format("and carNum in(select carframeNum from Vehicle where licenseNum like '%%%s%%') ",
                bankCard.getCarNum());
    }

    hql += " order by " + order;

    if (BooleanUtils.isFalse(rank)) {
        hql += " desc ";
    }

    Session session = HibernateSessionFactory.getSession();
    Query query = session.createQuery(hql);
    Query query2 = session.createQuery("select count(*) " + hql);

    long count = (long) query2.uniqueResult();

    Page page = PageUtil.createPage(30, (int) count, currentPage);

    query.setFirstResult(page.getBeginIndex());
    query.setMaxResults(page.getEveryPage());

    List<BankCard> cardList = query.list();

    HibernateSessionFactory.closeSession();

    request.setAttribute("list", cardList);
    request.setAttribute("page", page);

    return SUCCESS;
}

From source file:com.dz.module.contract.ContractDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from  w w w.j  a va  2  s . co  m
public List<Contract> contractSearch(Page page) throws HibernateException {
    List<Contract> l = new ArrayList<Contract>();
    Session session = null;
    Transaction tx = null;
    try {
        session = HibernateSessionFactory.getSession();
        tx = (Transaction) session.beginTransaction();
        Query query = session.createQuery("from Contract");
        query.setMaxResults(15);
        query.setFirstResult(page.getBeginIndex());
        l = query.list();
        query = null;
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        HibernateSessionFactory.closeSession();
    }
    return l;
}

From source file:com.dz.module.contract.ContractDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from   www.j  a v  a  2  s. c  o  m
public List<Contract> contractSearchAvilable(Page page) throws HibernateException {
    List<Contract> l = new ArrayList<Contract>();
    Session session = null;
    Transaction tx = null;
    try {
        session = HibernateSessionFactory.getSession();
        tx = (Transaction) session.beginTransaction();
        Query query = session.createQuery("from Contract where state in (0,1)");
        query.setMaxResults(15);
        query.setFirstResult(page.getBeginIndex());
        l = query.list();
        query = null;
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        HibernateSessionFactory.closeSession();
    }
    return l;
}