Example usage for org.hibernate Criteria list

List of usage examples for org.hibernate Criteria list

Introduction

In this page you can find the example usage for org.hibernate Criteria list.

Prototype

public List list() throws HibernateException;

Source Link

Document

Get the results.

Usage

From source file:agenda.Dao.DaoPessoa.java

public List consultaTelefones(Pessoa p) {
    sessao = HibernateUtil.getSessionFactory().openSession();
    List<String> telefones = new ArrayList<>();
    List<Pessoa> pessoas = new ArrayList<>();
    try {/*w w w. ja va2 s  .c om*/
        trans = sessao.beginTransaction();
        Criteria c = sessao.createCriteria(Pessoa.class);
        pessoas = c.list();
        for (int i = 0; i < pessoas.size(); i++) {
            Pessoa daLista = pessoas.get(i);
            if (daLista.getNome().equals(p.getNome())) {
                telefones.addAll(daLista.getTelefone());
            }
        }

    } catch (Exception e) {

    } finally {
        sessao.close();
    }
    return telefones;
}

From source file:ajax.getProduct.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// www .  j  a v a 2s  .c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        try (PrintWriter out = response.getWriter()) {
//            String pcode = request.getParameter("pcode");
//            if (pcode != null && pcode.equals("")) {
//                Session con = FactoryManager.getSessionFactory().openSession();
//                Criteria cri = con.createCriteria(Products.class);
//                cri.add(Restrictions.eq("prodCode", pcode));
//                Products p = (Products) cri.list().get(0);
//
//                String resptext = p.getItmCode() + "," + p.getBrand().getBrandName() + "," + p.getCategory().getCatName();
//                out.write(resptext);
////                System.out.println(resptext);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try (PrintWriter out = resp.getWriter()) {
        String pcode = req.getParameter("pcode");
        if (pcode != null && !pcode.equals("")) {
            Session con = FactoryManager.getSessionFactory().openSession();
            Criteria cri = con.createCriteria(Products.class);
            cri.add(Restrictions.eq("prodCode", pcode));
            Products p = (Products) cri.list().get(0);

            String resptext = p.getItmCode() + "-" + p.getItmName() + "-" + p.getBrand().getBrandName() + "-"
                    + p.getCategory().getCatName();
            out.write(resptext);
        } else {
            out.write("0");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:akvelon.domain.dao.UsersDAOImpl.java

@Override
public List<Users> getList() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Criteria crit = session.createCriteria(Users.class);
    List<Users> uList = (List<Users>) crit.list();
    session.close();/*from   w  w  w  . j a  va2 s .c  o  m*/
    return uList;
}

From source file:alma.acs.tmcdb.TestPojosPersistence.java

License:Open Source License

public void testCriteriaAPI() throws Exception {

    createDB();//from www.  j a  va2  s.  c  o  m

    try {
        createConfigurationComputerAndTwoNetworkDevices();

        Configuration config = (Configuration) hibernateUtil.getList(Configuration.class).iterator().next();
        assertNotNull(config);

        // Now we test that using the criteria API we can find our objects
        Criteria c = hibernateUtil.getSession().createCriteria(NetworkDevice.class);
        c.add(Restrictions.eq("name", "wall-e"));
        assertEquals(2, c.list().size());

        c = hibernateUtil.getSession().createCriteria(NetworkDevice.class);
        c.add(Restrictions.eq("name", "wall-e"));
        c.add(Restrictions.eq("networkName", "wall-e.eso.org"));
        assertEquals(1, c.list().size());

        c = hibernateUtil.getSession().createCriteria(NetworkDevice.class);
        c.add(Restrictions.eq("configuration", config));
        assertEquals(3, c.list().size());

        c = hibernateUtil.getSession().createCriteria(Configuration.class);
        c.add(Restrictions.eq("configurationName", "rtobarConfig"));
        c.add(Restrictions.lt("creationTime", new Date()));
        assertEquals(1, c.list().size());

        try {
            c = hibernateUtil.getSession().createCriteria(Configuration.class);
            c.add(Restrictions.eq("configuratioName", "rtobarConfig")); // typo: should be configurationName
            c.list();
            fail("Should fail, property 'configuratioName' doesn't exist for Configuration objects");
        } catch (QueryException e) {
        }

    } finally {
        dropDB();
    }

}

From source file:alpha.portal.dao.hibernate.AlphaCardDaoHibernate.java

License:Apache License

/**
 * List alpha cards by criterion./* w w  w.  j  av a 2s.  c  o  m*/
 * 
 * @param caseId
 *            the case id
 * @param criteriaArray
 *            the criteria array
 * @return the list
 * @see alpha.portal.dao.AlphaCardDao#listAlphaCardsByCriterion(org.hibernate.criterion.Criterion)
 */
public List<AlphaCard> listAlphaCardsByCriterion(final String caseId, final Criterion... criteriaArray) {
    Session session;
    boolean sessionOwn = false;
    try {
        session = this.getSessionFactory().getCurrentSession();
    } catch (final Exception e) {
        session = this.getSessionFactory().openSession();
        sessionOwn = true;
    }

    // get newest sequenceNumber for each cardId
    final DetachedCriteria version = DetachedCriteria.forClass(AlphaCard.class, "cardVersion")
            .add(Property.forName("card.alphaCardIdentifier.cardId")
                    .eqProperty("cardVersion.alphaCardIdentifier.cardId"))
            .setProjection(
                    Projections.projectionList().add(Projections.max("alphaCardIdentifier.sequenceNumber")));

    final Criteria crit = session.createCriteria(AlphaCard.class, "card");
    for (final Criterion c : criteriaArray) {
        // Create the subquery (somehow we need to use the Descriptor or
        // else the subquery-JOIN is not done)
        final DetachedCriteria subcrit = DetachedCriteria.forClass(AlphaCardDescriptor.class, "crit");

        // Join the adornments
        subcrit.createAlias("crit.adornmentList", "ad");

        // Add adornment condition
        subcrit.add(c);

        // Map the subquery back to the outer query
        subcrit.add(Restrictions.eqProperty("card.alphaCardIdentifier", "crit.alphaCardIdentifier"));

        // Narrow down subquery or else we get a NullPointer-Exception
        subcrit.setProjection(Projections.property("crit.alphaCardIdentifier.cardId"));

        // Add this subquery to the outer query.
        crit.add(Subqueries.exists(subcrit));
    }
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            .add(Property.forName("alphaCardIdentifier.sequenceNumber").eq(version))
            .createAlias("alphaCase", "case").add(Restrictions.eq("case.caseId", caseId));

    List<AlphaCard> list = crit.list();
    if (list.size() > 1) {
        final List<AlphaCard> order = (list.get(0)).getAlphaCase().getAlphaCards();
        final List<AlphaCard> orderedList = new LinkedList<AlphaCard>();
        for (final AlphaCard cc : order) {
            for (final AlphaCard c : list) {
                if (c.getAlphaCardIdentifier().equals(cc.getAlphaCardIdentifier())) {
                    orderedList.add(c);
                    break;
                }
            }
        }
        list = orderedList;
    }

    if (sessionOwn) {
        session.close();
    }

    return list;
}

From source file:analysers.MarketValueAnalyser.java

License:Open Source License

public List<Double> createMarginalDistribution(double lower, double upper, int days,
        MarketValueAnalyser.Analyse period, boolean good_rep, PrintWriter writer) {

    HibernateSupport.beginTransaction();
    Criteria c2 = HibernateSupport.getCurrentSession().createCriteria(News.class);
    c2.createAlias("news_details", "detail");
    c2.add(Restrictions.ge("detail.total_polarity", lower));
    c2.add(Restrictions.lt("detail.total_polarity", upper));

    if (good_rep) {
        c2.createAlias("companies", "company");
        c2.add(News.getNewsOfCompaniesWithGoodReputation());
    }/*from   w  w  w. ja  va2 s .co  m*/

    List<News> news_list = c2.list();
    HibernateSupport.commitTransaction();

    System.out.println("list.size() = " + news_list.size());

    PolynomialSplineFunction psf;
    Date publish_date;
    Calendar from = Calendar.getInstance();
    Calendar to = Calendar.getInstance();
    double[] share_price_dev;
    int counter = 0;
    News single_news;
    List<Company> companies;
    List<Double> price_devs_period = new ArrayList<Double>();
    Pair<Calendar, Calendar> from_to;

    while (news_list.size() > 0) {
        single_news = news_list.get(0);
        news_list.remove(0);

        companies = single_news.getCompaniesNew();

        publish_date = single_news.getDate();
        //from.setTime(publish_date);
        //to.setTime(publish_date);

        from_to = MyDateUtils.getFromToCalendars(period, publish_date, days);
        from = from_to.getValue0();
        to = from_to.getValue1();

        to.set(Calendar.DAY_OF_YEAR, to.get(Calendar.DAY_OF_YEAR) + days);
        for (Company company : single_news.getCompaniesNew()) {
            //System.out.println("publish_date = " + publish_date);
            //System.out.println("ISIN = " + company.getIsin());
            if ((psf = this.getMarketValueSplineFromTo(company, from, to)) != null) {
                share_price_dev = this.getSharePriceDevelopement(psf, from, to);
                //System.out.println(++counter);
                //System.out.println(share_price_dev[days - 1]);
                price_devs_period.add(share_price_dev[days - 1]); //day - 1
                writer.println(single_news.getNewsDetails().get(0).getTotalPolarity() + ", "
                        + share_price_dev[days - 1]);
            }
        }
    }

    /*Collections.sort(price_devs_period);
    List<Double> data_set = this.createDataSet(price_devs_period, -10.0f, 10.0f, 42);
    System.out.println(data_set);
    return data_set;*/
    return null;

}

From source file:Api.GetTest.java

/**
 * Retrieves representation of an instance of Api.GetTest
 *
 * @return an instance of java.lang.String
 *//*  w  ww .  ja  v  a2  s  .  c om*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getJson() {
    SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    Session s = sessionFactory.openSession();
    Criteria cr = s.createCriteria(FirstSubcategory.class);
    List results = cr.list();
    JSONSerializer serializer = new JSONSerializer();
    sessionFactory.close();
    return serializer.exclude("*.class").serialize(results);
}

From source file:API.Login.java

@Path("Auth")
@GET//  w w w.j ava  2s  .  co  m
public void auth(@QueryParam("uname") String uname, @QueryParam("password") String pwd) {
    String path = "";
    try {
        Session se = NewHibernateUtil.getSessionFactory().openSession();
        Transaction t = se.beginTransaction();

        Criteria cr = se.createCriteria(LoginTable.class);

        cr.add(Restrictions.eq("username", uname));
        cr.add(Restrictions.eq("password", pwd));

        ArrayList<LoginTable> al = (ArrayList<LoginTable>) cr.list();

        if (al.size() > 0) {
            path = "index.html";
        } else {
            String msg = "" + "Try Again";
            path = "Login.jsp";
        }
        t.commit();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:apm.common.core.DaoImpl.java

License:Open Source License

/**
 * //from   w w w .  j  av a  2s  .c om
 * @param page
 * @param detachedCriteria
 * @param resultTransformer
 * @return
 */
@SuppressWarnings("unchecked")
public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria, ResultTransformer resultTransformer) {
    // get count
    if (!page.isDisabled() && !page.isNotCount()) {
        page.setCount(count(detachedCriteria));
        if (page.getCount() < 1) {
            return page;
        }
    }
    Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
    criteria.setResultTransformer(resultTransformer);
    // set page
    if (!page.isDisabled()) {
        criteria.setFirstResult(page.getFirstResult());
        criteria.setMaxResults(page.getMaxResults());
    }
    // order by
    if (StringUtils.isNotBlank(page.getOrderBy())) {
        for (String order : StringUtils.split(page.getOrderBy(), ",")) {
            String[] o = StringUtils.split(order, " ");
            if (o.length == 1) {
                criteria.addOrder(Order.asc(o[0]));
            } else if (o.length == 2) {
                if ("DESC".equals(o[1].toUpperCase())) {
                    criteria.addOrder(Order.desc(o[0]));
                } else {
                    criteria.addOrder(Order.asc(o[0]));
                }
            }
        }
    }
    page.setList(criteria.list());
    return page;
}

From source file:apm.common.core.DaoImpl.java

License:Open Source License

/**
 * // ww w.  j  a  v  a 2  s .c  om
 * @param detachedCriteria
 * @param resultTransformer
 * @return
 */
@SuppressWarnings("unchecked")
public List<T> find(DetachedCriteria detachedCriteria, ResultTransformer resultTransformer) {
    Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
    criteria.setResultTransformer(resultTransformer);
    return criteria.list();
}