Example usage for org.hibernate Criteria add

List of usage examples for org.hibernate Criteria add

Introduction

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

Prototype

public Criteria add(Criterion criterion);

Source Link

Document

Add a Criterion restriction to constrain the results to be retrieved.

Usage

From source file:AdminSystemClasses.CustomerInfoGenerator.java

/**
 * A thing that generates a BankAccount for a BankCustomer
 * I made this a separate method because it would be useful to
 * have if a customer could have multiple accounts.
 * /* ww  w .j  ava2s  . c om*/
 * @param cus BankCustomer to generate BankAccount for
 * @return BankAccount generated and now associated to cus
 * @throws HibernateException 
 */
private static BankAccount generateAccount(BankCustomer cus) throws HibernateException {
    Random rand = new Random(System.currentTimeMillis());
    Integer c1, c2, acctId, pin;
    String card;
    BankAccount acct;
    Session s = bank.DB.getSession();
    Criteria cr;
    List l;

    do {
        acctId = rand.nextInt(100000000);
        cr = s.createCriteria(BankAccount.class);
        cr.add(Restrictions.eq("accountid", acctId));
        l = cr.list();
    } while (!l.isEmpty());

    do {
        c1 = rand.nextInt(100000000);
        c2 = rand.nextInt(100000000);
        card = String.format("%08d", c1) + String.format("%08d", c2);
        cr = s.createCriteria(BankAccount.class);
        cr.add(Restrictions.eq("cardnumber", card));
        l = cr.list();
    } while (!l.isEmpty());

    pin = rand.nextInt(10000);

    acct = new BankAccount(acctId, cus, new BigDecimal(0), String.format("%04d", pin), card);

    cus.addBankAccount(acct);
    return acct;
}

From source file:AdminSystemClasses.EditATM.java

@Override
public String execute() {
    String msg = null;//from   w ww  .j  a v a  2 s  .c om
    Session sf = DB.getSession();
    Transaction tx = sf.beginTransaction();
    // atm = (BankATM)sf.load(BankATM.class, getAtmId());
    Criteria cr = sf.createCriteria(BankATM.class);
    cr.add(Restrictions.eq("id", getAtmId()));
    if (cr.list().size() > 0) {
        atm = cr.list();

        msg = "success";
    } else {
        msg = "failed";
    }

    return msg;

}

From source file:ajax.getProduct.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   ww  w  .j a  v  a  2s  .com
 * @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:alma.acs.tmcdb.TestPojosPersistence.java

License:Open Source License

public void testCriteriaAPI() throws Exception {

    createDB();//  w  w  w  . j  a v a 2  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./*www.j a v a 2  s.  c  om*/
 * 
 * @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   www  .ja va 2 s  . c  o 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:analysers.MarketValueAnalyser.java

License:Open Source License

public static void main(String[] args) throws ParseException {

    HibernateSupport.beginTransaction();
    Criteria cr = HibernateSupport.getCurrentSession().createCriteria(News.class);
    cr.createAlias("news_details", "details");
    cr.add(Restrictions.ge("details.total_objectivity", 0.5));
    cr.add(Restrictions.le("details.total_objectivity", 1.0));
    cr.setProjection(Projections.rowCount());
    long size = (long) cr.uniqueResult();
    HibernateSupport.commitTransaction();

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

    MarketValueAnalyser mva = new MarketValueAnalyser();
    //mva.createDistributionTable(40, 1, MarketValueAnalyser.Analyse.AFTER, false);
    mva.createDistributionTable(40, 3, MarketValueAnalyser.Analyse.AFTER, false);
    mva.createDistributionTable(40, 5, MarketValueAnalyser.Analyse.AFTER, false);
    mva.createDistributionTable(40, 7, MarketValueAnalyser.Analyse.AFTER, false);

    mva.createDistributionTable(40, 1, MarketValueAnalyser.Analyse.BEFORE, false);
    mva.createDistributionTable(40, 3, MarketValueAnalyser.Analyse.BEFORE, false);
    mva.createDistributionTable(40, 5, MarketValueAnalyser.Analyse.BEFORE, false);
    mva.createDistributionTable(40, 7, MarketValueAnalyser.Analyse.BEFORE, false);

}

From source file:API.Login.java

@Path("Auth")
@GET/*from  w w  w . ja  v  a2 s .  c o  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:appointment.data.ObjectFactory.java

public List<Object> getDataResourceList(Class resourceClass, String column, String value) {
    Session session = factory.openSession();
    Criteria criteria = session.createCriteria(resourceClass);
    criteria.add(Expression.eq(column, value));
    List<Object> dataObjects = criteria.list();
    return dataObjects;
}

From source file:appointment.data.ObjectFactory.java

public List<Object> getDataResourceList(Class resourceClass, HashMap<String, Object> criteriaList) {
    Session session = factory.openSession();
    Criteria criteria = session.createCriteria(resourceClass);
    for (String k : criteriaList.keySet()) {
        criteria.add(Expression.eq(k, criteriaList.get(k)));
    }/*  www .ja  v  a 2 s .co m*/
    List<Object> dataObjects = criteria.list();
    return dataObjects;
}