Example usage for org.hibernate Criteria setProjection

List of usage examples for org.hibernate Criteria setProjection

Introduction

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

Prototype

public Criteria setProjection(Projection projection);

Source Link

Document

Used to specify that the query results will be a projection (scalar in nature).

Usage

From source file:com.floreantpos.report.service.ReportService.java

License:Open Source License

public SalesDetailedReport getSalesDetailedReport(Date fromDate, Date toDate) {
    GenericDAO dao = new GenericDAO();
    SalesDetailedReport report = new SalesDetailedReport();
    Session session = null;//from w w  w . java  2s .c om

    report.setFromDate(fromDate);
    report.setToDate(toDate);
    report.setReportTime(new Date());
    try {

        session = dao.getSession();

        Criteria criteria = session.createCriteria(DrawerPullReport.class);
        criteria.add(Restrictions.ge(DrawerPullReport.PROP_REPORT_TIME, fromDate));
        criteria.add(Restrictions.le(DrawerPullReport.PROP_REPORT_TIME, toDate));
        List list = criteria.list();
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            DrawerPullReport drawerPullReport = (DrawerPullReport) iter.next();
            DrawerPullData data = new DrawerPullData();
            data.setDrawerPullId(drawerPullReport.getId());
            data.setTicketCount(drawerPullReport.getTicketCount());
            data.setIdealAmount(drawerPullReport.getDrawerAccountable());
            data.setActualAmount(drawerPullReport.getCashToDeposit());
            data.setVarinceAmount(
                    drawerPullReport.getDrawerAccountable() - drawerPullReport.getCashToDeposit());
            report.addDrawerPullData(data);
        }

        criteria = session.createCriteria(CreditCardTransaction.class);
        criteria.add(Restrictions.ge(CreditCardTransaction.PROP_TRANSACTION_TIME, fromDate));
        criteria.add(Restrictions.le(CreditCardTransaction.PROP_TRANSACTION_TIME, toDate));
        list = criteria.list();

        for (Iterator iter = list.iterator(); iter.hasNext();) {
            CreditCardTransaction t = (CreditCardTransaction) iter.next();
            report.addCreditCardData(t);
        }

        criteria = session.createCriteria(DebitCardTransaction.class);
        criteria.add(Restrictions.ge(DebitCardTransaction.PROP_TRANSACTION_TIME, fromDate));
        criteria.add(Restrictions.le(DebitCardTransaction.PROP_TRANSACTION_TIME, toDate));
        list = criteria.list();

        for (Iterator iter = list.iterator(); iter.hasNext();) {
            DebitCardTransaction t = (DebitCardTransaction) iter.next();
            report.addCreditCardData(t);
        }

        criteria = session.createCriteria(GiftCertificateTransaction.class);
        criteria.add(Restrictions.ge(GiftCertificateTransaction.PROP_TRANSACTION_TIME, fromDate));
        criteria.add(Restrictions.le(GiftCertificateTransaction.PROP_TRANSACTION_TIME, toDate));
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.rowCount());
        projectionList.add(Projections.sum(GiftCertificateTransaction.PROP_AMOUNT));
        criteria.setProjection(projectionList);
        Object[] object = (Object[]) criteria.uniqueResult();
        if (object != null && object.length > 0 && object[0] instanceof Number) {
            report.setGiftCertReturnCount(((Number) object[0]).intValue());
        }
        if (object != null && object.length > 1 && object[1] instanceof Number) {
            report.setGiftCertReturnAmount(((Number) object[1]).doubleValue());
        }

        criteria = session.createCriteria(GiftCertificateTransaction.class);
        criteria.add(Restrictions.ge(GiftCertificateTransaction.PROP_TRANSACTION_TIME, fromDate));
        criteria.add(Restrictions.le(GiftCertificateTransaction.PROP_TRANSACTION_TIME, toDate));
        criteria.add(
                Restrictions.gt(GiftCertificateTransaction.PROP_GIFT_CERT_CASH_BACK_AMOUNT, Double.valueOf(0)));
        projectionList = Projections.projectionList();
        projectionList.add(Projections.rowCount());
        projectionList.add(Projections.sum(GiftCertificateTransaction.PROP_GIFT_CERT_CASH_BACK_AMOUNT));
        criteria.setProjection(projectionList);
        object = (Object[]) criteria.uniqueResult();
        if (object != null && object.length > 0 && object[0] instanceof Number) {
            report.setGiftCertChangeCount(((Number) object[0]).intValue());
        }
        if (object != null && object.length > 1 && object[1] instanceof Number) {
            report.setGiftCertChangeAmount(((Number) object[1]).doubleValue());
        }

        criteria = session.createCriteria(Ticket.class);
        criteria.createAlias(Ticket.PROP_GRATUITY, "g"); //$NON-NLS-1$
        criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, fromDate));
        criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, toDate));
        criteria.add(Restrictions.gt("g." + Gratuity.PROP_AMOUNT, Double.valueOf(0))); //$NON-NLS-1$
        projectionList = Projections.projectionList();
        projectionList.add(Projections.rowCount());
        projectionList.add(Projections.sum("g." + Gratuity.PROP_AMOUNT)); //$NON-NLS-1$
        criteria.setProjection(projectionList);
        object = (Object[]) criteria.uniqueResult();
        if (object != null && object.length > 0 && object[0] instanceof Number) {
            report.setTipsCount(((Number) object[0]).intValue());
        }
        if (object != null && object.length > 1 && object[1] instanceof Number) {
            report.setChargedTips(((Number) object[1]).doubleValue());
        }

        criteria = session.createCriteria(Ticket.class);
        criteria.createAlias(Ticket.PROP_GRATUITY, "g"); //$NON-NLS-1$
        criteria.add(Restrictions.ge(Ticket.PROP_CREATE_DATE, fromDate));
        criteria.add(Restrictions.le(Ticket.PROP_CREATE_DATE, toDate));
        criteria.add(Restrictions.gt("g." + Gratuity.PROP_AMOUNT, Double.valueOf(0))); //$NON-NLS-1$
        criteria.add(Restrictions.gt("g." + Gratuity.PROP_PAID, Boolean.TRUE)); //$NON-NLS-1$
        projectionList = Projections.projectionList();
        projectionList.add(Projections.sum("g." + Gratuity.PROP_AMOUNT)); //$NON-NLS-1$
        criteria.setProjection(projectionList);
        object = (Object[]) criteria.uniqueResult();
        if (object != null && object.length > 0 && object[0] instanceof Number) {
            report.setTipsPaid(((Number) object[0]).doubleValue());
        }

        return report;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:com.fourgenius.www.public_access.registration.student.Jp_registration_student_informations.java

private String generate_student_id() {

    String branch;//from   w  ww.ja v  a  2s  . c o m
    String level;
    String course;
    String batch;
    String group;
    String year;
    String weekOrEnd;
    long regNo;
    String preid;

    if (_rb_registration_student_information_form_colombo.isSelected()) {
        branch = "C";
    } else if (_rb_registration_student_information_form_negombo.isSelected()) {
        branch = "N";
    } else {
        branch = "K";
    }

    if (_cb_registration_student_personalInformations_studentDetails_course_level.getSelectedItem().toString()
            .equals("Diploma Level")) {
        level = "";
    } else {
        String[] lid = _cb_registration_student_personalInformations_studentDetails_course_level
                .getSelectedItem().toString().split("-");
        level = lid[1].toString();
    }

    String[] cid = _cb_registration_student_personalInformations_studentDetails_course.getSelectedItem()
            .toString().split("-");
    course = cid[1].toString();

    batch = _cb_registration_student_batch.getSelectedItem().toString();

    group = _cb_registration_student_group.getSelectedItem().toString();

    String as = _yc_student_registration_year.getYear() + "";
    String ye[] = as.split("");
    year = ye[2] + ye[3];

    weekOrEnd = _cb_registration_student_weekOrEnd.getSelectedItem().toString();

    Criteria c = s.createCriteria(StuInfoPersonal.class);
    if (level.equals("G") || level.equals("I")) {

        preid = branch + level + course + "-" + new SimpleDateFormat("ddMMyyyy").format(new Date());
        c.add(Restrictions.like("stuUserInfoId", preid + "%"));

    } else {

        if (level.equals("")) {

            preid = branch + course + "-" + batch + group + "-" + year + "-" + weekOrEnd;
            c.add(Restrictions.like("stuUserInfoId", preid + "%"));

        } else {

            preid = branch + level + course + "-" + batch + group + "-" + year + "-" + weekOrEnd;
            c.add(Restrictions.like("stuUserInfoId", preid + "%"));

        }

    }

    regNo = (long) c.setProjection(Projections.rowCount()).uniqueResult() + 1;

    String ID = preid + "-" + regNo;

    _lb_registration_student_preview_studentID.setText(ID);

    //        String id = "ID";
    //        String st = "ST";
    //        stu_user_info user_info = new stu_user_info();
    //        String countid = user_info.getStu_user_info_id();
    //        int idcount = Integer.parseInt(countid);
    //        int id_no = ++idcount;
    //
    //        String a = Integer.toString(id_no);
    //        int length = a.length();
    //        System.out.println(length);
    //
    //        String idn = Integer.toString(id_no);
    //        String zeros;
    //        if (length == 1) {
    //            zeros = "00000";
    //        } else if (length == 2) {
    //            zeros = "0000";
    //        } else if (length == 3) {
    //            zeros = "000";
    //        } else if (length == 4) {
    //            zeros = "00";
    //        } else if (length == 5) {
    //            zeros = "0";
    //        } else {
    //            zeros = "";
    //        }
    //
    //        if (_rb_registration_student_information_form_colombo.isSelected()) {
    //            branch_name = "COL";
    //        } else {
    //            branch_name = "KAN";
    //        }
    //        String lecture_id = id + "-" + st + "-" + branch_name + "-" + zeros + idn;
    //        _lb_registration_student_preview_studentID.setText(lecture_id);
    return ID;

}

From source file:com.gisgraphy.domain.repository.GenericGisDao.java

License:Open Source License

/**
 * base method for all findNearest* /*from ww w.j  a  v a 2s  .co m*/
 * 
 * @param point
 *                The point from which we want to find GIS Object
 * @param pointId
 *                the id of the point that we don't want to be include, it
 *                is used to not include the gisFeature from which we want
 *                to find the nearest
 * @param distance
 *                distance The radius in meters
 * @param firstResult
 *                the firstResult index (for pagination), numbered from 1,
 *                if < 1 : it will not be taken into account
 * @param maxResults
 *                The Maximum number of results to retrieve (for
 *                pagination), if <= 0 : it will not be taken into acount
 * @param requiredClass
 *                the class of the object to be retireved
 * @param isMunicipality whether we should filter on city that are flag as 'municipality'.
          act as a filter, if false it doesn't filters( false doesn't mean that we return non municipality)
 * @return A List of GisFeatureDistance with the nearest elements or an
 *         emptylist (never return null), ordered by distance.<u>note</u>
 *         the specified gisFeature will not be included into results
 * @see GisFeatureDistance
 * @return a list of gisFeature (never return null but an empty list)
 */
@SuppressWarnings("unchecked")
protected List<GisFeatureDistance> getNearestAndDistanceFrom(final Point point, final Long pointId,
        final double distance, final int firstResult, final int maxResults, final boolean includeDistanceField,
        final Class<? extends GisFeature> requiredClass, final boolean isMunicipality) {
    Assert.notNull(point);
    return (List<GisFeatureDistance>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            Criteria criteria = session.createCriteria(requiredClass);

            if (maxResults > 0) {
                criteria = criteria.setMaxResults(maxResults);
            }
            if (firstResult >= 1) {
                criteria = criteria.setFirstResult(firstResult - 1);
            }
            criteria = criteria.add(new DistanceRestriction(point, distance));
            List<String> fieldList = IntrospectionHelper.getFieldsAsList(requiredClass);
            ProjectionList projections = ProjectionBean.fieldList(fieldList, true);
            if (includeDistanceField) {
                projections.add(SpatialProjection.distance_sphere(point, GisFeature.LOCATION_COLUMN_NAME)
                        .as("distance"));
            }
            criteria.setProjection(projections);
            if (pointId != 0) {
                // remove The From Point
                criteria = criteria.add(Restrictions.not(Restrictions.idEq(pointId)));
            }
            if (includeDistanceField) {
                criteria.addOrder(new ProjectionOrder("distance"));
            }
            if (isMunicipality && (requiredClass == City.class || requiredClass == GisFeature.class)) {
                criteria.add(Restrictions.eq(City.MUNICIPALITY_FIELD_NAME, isMunicipality));
            }

            criteria.setCacheable(true);
            List<Object[]> queryResults = criteria.list();

            String[] aliasList;
            if (includeDistanceField) {
                aliasList = (String[]) ArrayUtils.add(IntrospectionHelper.getFieldsAsArray(requiredClass),
                        "distance");
            } else {
                aliasList = IntrospectionHelper.getFieldsAsArray(requiredClass);
            }
            int idPropertyIndexInAliasList = 0;
            for (int i = 0; i < aliasList.length; i++) {
                if (aliasList[i] == "id") {
                    idPropertyIndexInAliasList = i;
                    break;
                }
            }

            boolean hasZipCodesProperty = ZipCodesAware.class.isAssignableFrom(requiredClass);
            Map<Long, Set<String>> idToZipCodesMap = null;
            if (hasZipCodesProperty && queryResults.size() > 0) {
                List<Long> ids = new ArrayList<Long>();
                for (Object[] tuple : queryResults) {
                    ids.add((Long) tuple[idPropertyIndexInAliasList]);
                }
                String zipCodeQuery = "SELECT code as code,gisfeature as id FROM "
                        + ZipCode.class.getSimpleName().toLowerCase() + " zip where zip.gisfeature in (:ids)";
                Query qry = session.createSQLQuery(zipCodeQuery).addScalar("code", Hibernate.STRING)
                        .addScalar("id", Hibernate.LONG);
                qry.setCacheable(true);

                qry.setParameterList("ids", ids);
                List<Object[]> zipCodes = (List<Object[]>) qry.list();

                if (zipCodes.size() > 0) {
                    idToZipCodesMap = new HashMap<Long, Set<String>>();
                    for (Object[] zipCode : zipCodes) {
                        Long idFromZipcode = (Long) zipCode[1];
                        Set<String> zipCodesFromMap = idToZipCodesMap.get(idFromZipcode);
                        if (zipCodesFromMap == null) {
                            Set<String> zipCodesToAdd = new HashSet<String>();
                            idToZipCodesMap.put(idFromZipcode, zipCodesToAdd);
                            zipCodesFromMap = zipCodesToAdd;
                        }
                        zipCodesFromMap.add((String) zipCode[0]);
                    }
                }
            }
            List<GisFeatureDistance> results = ResultTransformerUtil.transformToGisFeatureDistance(aliasList,
                    queryResults, idToZipCodesMap, requiredClass);
            return results;
        }
    });

}

From source file:com.gisgraphy.domain.repository.OpenStreetMapDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<StreetDistance> getNearestAndDistanceFrom(final Point point, final double distance,
        final int firstResult, final int maxResults, final StreetType streetType, final Boolean oneWay,
        final String name, final StreetSearchMode streetSearchMode, final boolean includeDistanceField) {
    if (streetSearchMode == StreetSearchMode.FULLTEXT && !GisgraphyConfig.STREET_SEARCH_FULLTEXT_MODE) {
        throw new GisgraphyException(
                "The fulltext mode has been removed in gisgraphy v 3.0 and has been replaced by fulltext webservice with placetype=street. please Consult user guide.");
    }//from ww  w . jav a2  s  . c om
    if (name != null && streetSearchMode == null) {
        throw new IllegalArgumentException("streetSearchmode can not be null if name is provided");
    }
    if (point == null && streetSearchMode == StreetSearchMode.CONTAINS) {
        throw new IllegalArgumentException(
                "you must specify lat/lng when streetsearchmode = " + StreetSearchMode.CONTAINS);
    }
    return (List<StreetDistance>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            Criteria criteria = session.createCriteria(OpenStreetMap.class);

            List<String> fieldList = IntrospectionHelper.getFieldsAsList(OpenStreetMap.class);

            ProjectionList projections = ProjectionBean.fieldList(fieldList, false);
            if (includeDistanceField && point != null) {
                projections.add(
                        //            SpatialProjection.distance_sphere(point, GisFeature.LOCATION_COLUMN_NAME).as(
                        //               "distance"));
                        SpatialProjection.distance_pointToLine(point, OpenStreetMap.SHAPE_COLUMN_NAME)
                                .as("distance"));
            }
            criteria.setProjection(projections);
            if (includeDistanceField && point != null) {
                criteria.addOrder(new ProjectionOrder("distance"));
            }
            if (maxResults > 0) {
                criteria = criteria.setMaxResults(maxResults);
            }
            if (firstResult >= 1) {
                criteria = criteria.setFirstResult(firstResult - 1);
            }
            if (point != null) {
                Polygon polygonBox = GeolocHelper.createPolygonBox(point.getX(), point.getY(), distance);
                criteria = criteria.add(new IntersectsRestriction(OpenStreetMap.SHAPE_COLUMN_NAME, polygonBox));
            }
            if (name != null) {
                if (streetSearchMode == StreetSearchMode.CONTAINS) {
                    criteria = criteria.add(Restrictions.isNotNull("name"));//optimisation!
                    criteria = criteria.add(
                            Restrictions.ilike(OpenStreetMap.FULLTEXTSEARCH_PROPERTY_NAME, "%" + name + "%"));
                    //criteria = criteria.add(new PartialWordSearchRestriction(OpenStreetMap.PARTIALSEARCH_VECTOR_COLUMN_NAME, name));
                } else if (streetSearchMode == StreetSearchMode.FULLTEXT) {
                    criteria = criteria.add(
                            new FulltextRestriction(OpenStreetMap.FULLTEXTSEARCH_VECTOR_PROPERTY_NAME, name));
                } else {
                    throw new NotImplementedException(
                            streetSearchMode + " is not implemented for street search");
                }
            }
            if (streetType != null) {
                criteria = criteria.add(Restrictions.eq("streetType", streetType));
            }
            if (oneWay != null) {
                criteria = criteria.add(Restrictions.eq("oneWay", oneWay));
            }
            criteria.setCacheable(true);
            // List<Object[]> queryResults =testCriteria.list();
            List<?> queryResults = criteria.list();

            if (queryResults != null && queryResults.size() != 0) {
                String[] propertiesNameArray;
                if (includeDistanceField && point != null) {
                    propertiesNameArray = (String[]) ArrayUtils
                            .add(IntrospectionHelper.getFieldsAsArray(OpenStreetMap.class), "distance");
                } else {
                    propertiesNameArray = IntrospectionHelper.getFieldsAsArray(OpenStreetMap.class);
                }
                List<StreetDistance> results = ResultTransformerUtil
                        .transformToStreetDistance(propertiesNameArray, queryResults);
                return results;
            } else {
                return new ArrayList<StreetDistance>();
            }

        }
    });
}

From source file:com.gisgraphy.hibernate.criterion.DistanceRestrictionTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test// w  ww.j  a  v a 2s .  c om
public void testDistanceRestrictionPointDouble() {
    final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L);
    City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L);

    this.cityDao.save(p1);
    this.cityDao.save(p2);

    HibernateCallback hibernateCallback = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(City.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            Projection projection = Projections.property("name").as("name");
            testCriteria.setProjection(projection).add(Restrictions.ne("id", p1.getId()))
                    .add(new DistanceRestriction(p1.getLocation(), 500000D))
                    .setResultTransformer(Transformers.aliasToBean(_CityDTO.class));

            List<_CityDTO> results = testCriteria.list();
            return results;
        }
    };

    List<_CityDTO> cities = (List<_CityDTO>) testDao.testCallback(hibernateCallback);
    assertEquals("According to the distance restriction, it should have zero result", 0, cities.size());

    hibernateCallback = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(City.class);
            Projection projection = Projections.property("name").as("name");
            testCriteria.setProjection(projection).add(new DistanceRestriction(p1.getLocation(), 600000D))
                    .add(Restrictions.ne("id", p1.getId()))
                    .setResultTransformer(Transformers.aliasToBean(_CityDTO.class));

            List<_CityDTO> results = testCriteria.list();
            return results;
        }
    };

    cities = (List<_CityDTO>) testDao.testCallback(hibernateCallback);
    assertEquals("According to the distance restriction, it should have one results", 1, cities.size());
    assertEquals("bordeaux", cities.get(0).getName());

}

From source file:com.gisgraphy.hibernate.criterion.FulltextRestrictionTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test/*from  ww w.j  a  va2  s.co  m*/
public void testFulltextRestriction() {
    OpenStreetMap streetOSM = createOpenStreetMap();
    openStreetMapDao.save(streetOSM);
    assertNotNull(openStreetMapDao.get(streetOSM.getId()));

    int numberOfLineUpdated = openStreetMapDao.updateTS_vectorColumnForStreetNameSearch();

    assertEquals("It should have 1 lines updated : one for partial and one for fulltext", 1,
            numberOfLineUpdated);

    HibernateCallback hibernateCallback = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new FulltextRestriction(OpenStreetMap.FULLTEXTSEARCH_VECTOR_PROPERTY_NAME,
                            "Champs elysees"))//case sensitive accent
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    List<_OpenstreetmapDTO> streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallback);
    assertEquals(
            "According to the fulltext restriction, it should have a result (it should be case insensitive,accent insensitive and '-' insensitive",
            1, streets.size());

    assertEquals("According to the fulltext restriction, the result is incorrect", streetOSM.getGid(),
            streets.get(0).getGid());

    HibernateCallback hibernateCallbackminusSign = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new FulltextRestriction(OpenStreetMap.FULLTEXTSEARCH_VECTOR_PROPERTY_NAME,
                            "Champs-elysees"))//'-'
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallbackminusSign);
    assertEquals("According to the fulltext restriction, it should have a result (it should be '-' insensitive",
            1, streets.size());

    assertEquals("According to the fulltext restriction, the result is incorrect", streetOSM.getGid(),
            streets.get(0).getGid());

    HibernateCallback hibernateCallbackZeroResult = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new FulltextRestriction(OpenStreetMap.FULLTEXTSEARCH_VECTOR_PROPERTY_NAME,
                            "Champ elysees"))//wrong word
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallbackZeroResult);
    assertEquals("According to the fulltext restriction, it should not have result ", 0, streets.size());

}

From source file:com.gisgraphy.hibernate.criterion.IntersectsRestrictionTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test//from   ww w. j  a  v  a 2s  .  c  o  m
public void testPartialWordRestriction() {
    OpenStreetMap streetOSM = createAndSaveStreet();

    HibernateCallback hibernateCallbackSuccess = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new IntersectsRestriction(OpenStreetMap.SHAPE_COLUMN_NAME,
                            GeolocHelper.createPolygonBox(6.94130445F, 50.91544865F, 10000)))
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    List<_OpenstreetmapDTO> streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallbackSuccess);
    assertEquals("According to the intersects restriction, it should have a result ", 1, streets.size());

    assertEquals("According to the intersects restriction, the result is incorrect", streetOSM.getGid(),
            streets.get(0).getGid());

    HibernateCallback hibernateCallbackFail = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new IntersectsRestriction(OpenStreetMap.SHAPE_COLUMN_NAME,
                            GeolocHelper.createPolygonBox(7.94130445F, 51.91544865F, 10000)))
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallbackFail);
    assertEquals("According to the intersects restriction, it should have no result ", 0, streets.size());

}

From source file:com.gisgraphy.hibernate.criterion.NativeSQLOrderTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test/*from ww w  .j  a  v  a2 s  .c  o  m*/
public void testNativeSQLOrderShouldSortAscByDefault() {
    final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L);
    City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L);

    City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L);
    this.cityDao.save(p1);
    this.cityDao.save(p2);
    this.cityDao.save(p3);
    HibernateCallback hibernateCallback = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(City.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            Projection projection = Projections.property("featureId").as("featureId");
            testCriteria.setProjection(projection).addOrder(new NativeSQLOrder("featureId"))
                    .setResultTransformer(Transformers.aliasToBean(_CityDTO.class));

            List<_CityDTO> results = testCriteria.list();
            return results;
        }
    };

    List<_CityDTO> cities = (List<_CityDTO>) testDao.testCallback(hibernateCallback);
    assertEquals(3, cities.size());
    assertEquals("1", cities.get(0).getFeatureId().toString());
    assertEquals("2", cities.get(1).getFeatureId().toString());
    assertEquals("3", cities.get(2).getFeatureId().toString());
}

From source file:com.gisgraphy.hibernate.criterion.NativeSQLOrderTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test/*from  w  w  w .ja  v a 2 s. co m*/
public void testNativeSQLOrderShouldSortDesc() {
    final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L);
    City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L);

    City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L);
    this.cityDao.save(p1);
    this.cityDao.save(p2);
    this.cityDao.save(p3);
    HibernateCallback hibernateCallback = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(City.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            Projection projection = Projections.property("featureId").as("featureId");
            testCriteria.setProjection(projection).addOrder(new NativeSQLOrder("featureId", false))
                    .setResultTransformer(Transformers.aliasToBean(_CityDTO.class));

            List<_CityDTO> results = testCriteria.list();
            return results;
        }
    };

    List<_CityDTO> cities = (List<_CityDTO>) testDao.testCallback(hibernateCallback);
    assertEquals(3, cities.size());
    assertEquals("3", cities.get(0).getFeatureId().toString());
    assertEquals("2", cities.get(1).getFeatureId().toString());
    assertEquals("1", cities.get(2).getFeatureId().toString());
}

From source file:com.gisgraphy.hibernate.criterion.PartialWordRestrictionTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test/*from w  w w . ja  v  a 2s. c om*/
public void testPartialWordRestriction() {
    GisgraphyConfig.PARTIAL_SEARH_EXPERIMENTAL = true;
    OpenStreetMap streetOSM = createOpenStreetMap();
    openStreetMapDao.save(streetOSM);
    assertNotNull(openStreetMapDao.get(streetOSM.getId()));

    int numberOfLineUpdated = openStreetMapDao.updateTS_vectorColumnForStreetNameSearch();
    assertEquals("It should have 2 lines updated : one for partial and one for fulltext", 2,
            numberOfLineUpdated);

    HibernateCallback hibernateCallback = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new PartialWordSearchRestriction(OpenStreetMap.PARTIALSEARCH_VECTOR_PROPERTY_NAME,
                            "elys"))//case sensitive accent
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    List<_OpenstreetmapDTO> streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallback);
    assertEquals(
            "According to the fulltext restriction, it should have a result (it should be case insensitive,accent insensitive and '-' insensitive",
            1, streets.size());

    assertEquals("According to the fulltext restriction, the result is incorrect", streetOSM.getGid(),
            streets.get(0).getGid());

    HibernateCallback hibernateCallbackminusSign = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new PartialWordSearchRestriction(OpenStreetMap.PARTIALSEARCH_VECTOR_PROPERTY_NAME,
                            "mps ely"))
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallbackminusSign);
    assertEquals("According to the fulltext restriction, it should have a result (it should be '-' insensitive",
            1, streets.size());

    assertEquals("According to the fulltext restriction, the result is incorrect", streetOSM.getGid(),
            streets.get(0).getGid());

    HibernateCallback hibernateCallbackZeroResult = new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {

            Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
            List<String> fieldList = new ArrayList<String>();
            fieldList.add("name");
            fieldList.add("gid");

            Projection projection = ProjectionBean.fieldList(fieldList, true);
            testCriteria.setProjection(projection)
                    .add(new PartialWordSearchRestriction(OpenStreetMap.PARTIALSEARCH_VECTOR_PROPERTY_NAME,
                            "elysees champs"))//wrong word
                    .setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));

            List<_OpenstreetmapDTO> results = testCriteria.list();
            return results;
        }
    };

    streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallbackZeroResult);
    assertEquals("According to the fulltext restriction, it should not have result ", 0, streets.size());
    GisgraphyConfig.PARTIAL_SEARH_EXPERIMENTAL = false;

}