List of usage examples for org.hibernate.criterion DetachedCriteria createAlias
public DetachedCriteria createAlias(String associationPath, String alias)
From source file:id.co.kmn.backend.dao.impl.CustomerDAOImpl.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from www .j av a 2 s.c om*/ public Customer getCustomerByOrder(id.co.kmn.backend.model.Order order) { DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class); criteria.createAlias("orders", "au"); criteria.add(Restrictions.eq("au.id", Long.valueOf(order.getId()))); return (Customer) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria)); }
From source file:kr.debop4j.access.repository.organization.CompanyCodeItemRepository.java
License:Apache License
public DetachedCriteria buildCriteria(Company company, String code, String name, String itemName, String itemValue) {//from ww w .j ava2 s . co m if (log.isDebugEnabled()) log.debug( "Criteria . company=[{}], code=[{}], name=[{}], itemName=[{}], itemValue=[{}]", company, code, name, itemName, itemValue); DetachedCriteria dc = DetachedCriteria.forClass(CompanyCodeItem.class); if (company != null) { dc.createAlias("code", "c"); CriteriaTool.addEq(dc, "c.company", company); } if (StringTool.isNotEmpty(code)) CriteriaTool.addEq(dc, "c.code", code); if (StringTool.isNotEmpty(name)) CriteriaTool.addEq(dc, "c.name", name); if (StringTool.isNotEmpty(itemName)) CriteriaTool.addEq(dc, "name", itemName); if (StringTool.isNotEmpty(itemValue)) CriteriaTool.addEq(dc, "value", itemValue); return dc; }
From source file:kr.debop4j.access.test.repository.CriteriaSampleTest.java
License:Apache License
@Test @Transactional(readOnly = true)//from w w w.ja v a 2s . com public void groupingTest() { DetachedCriteria dc = DetachedCriteria.forClass(Employee.class); dc.createAlias("company", "c").createAlias("empGrade", "eg") .setProjection(Projections.projectionList().add(Projections.groupProperty("c.code")) .add(Projections.groupProperty("eg.code")).add(Projections.rowCount())); List loaded = dc.getExecutableCriteria(hibernateDao.getSession()).list(); log.info("Group by = [{}]", loaded); }
From source file:kr.debop4j.access.test.repository.CriteriaSampleTest.java
License:Apache License
@Test @Transactional/*from w w w .j a va 2 s . c o m*/ public void deleteTest() { DetachedCriteria dc = DetachedCriteria.forClass(Employee.class); dc.createAlias("empGrade", "eg").add(Restrictions.eq("eg.code", "GRD001")); hibernateDao.deleteAll(Employee.class, dc); }
From source file:net.greenrivers.hibernate.manytomany.CreateTest.java
@After public void tearDown() { HibernateTemplate hibernateTemplate = (HibernateTemplate) SpringContextHolder.ctx .getBean("hibernateTemplate"); DetachedCriteria findCertified = DetachedCriteria.forClass(Certified.class); findCertified.createAlias("category", "c"); findCertified.createAlias("license", "l"); findCertified.add(Restrictions.eq("c.name", "Category-1")); findCertified.add(Restrictions.eq("l.name", "License-2")); List certifies = hibernateTemplate.findByCriteria(findCertified); Certified cert1 = (Certified) certifies.get(0); hibernateTemplate.delete(cert1);//from w w w .j a v a2s .c o m DetachedCriteria findCategory = DetachedCriteria.forClass(Category.class); findCategory.add(Restrictions.eq("name", "Category-1")); List categories = hibernateTemplate.findByCriteria(findCategory); Category cat1 = (Category) categories.get(0); hibernateTemplate.delete(cat1); DetachedCriteria findLicense = DetachedCriteria.forClass(License.class); findLicense.add(Restrictions.eq("name", "License-2")); List licenses = hibernateTemplate.findByCriteria(findLicense); License lic2 = (License) licenses.get(0); hibernateTemplate.delete(lic2); }
From source file:net.greenrivers.hibernate.manytomany.CreateTest.java
@Test public void testHappy() { HibernateTemplate hibernateTemplate = (HibernateTemplate) SpringContextHolder.ctx .getBean("hibernateTemplate"); DetachedCriteria findCategory = DetachedCriteria.forClass(Category.class); findCategory.add(Restrictions.eq("name", "Category-1")); List categories = hibernateTemplate.findByCriteria(findCategory); Category cat1 = (Category) categories.get(0); assertNotNull(cat1);//from w ww .j a v a2 s . c om DetachedCriteria findLicense = DetachedCriteria.forClass(License.class); findLicense.add(Restrictions.eq("name", "License-2")); List licenses = hibernateTemplate.findByCriteria(findLicense); License lic2 = (License) licenses.get(0); assertNotNull(lic2); Certified cert1 = new Certified(); cert1.setCategory(cat1); cert1.setLicense(lic2); cert1.setIsDefault(Boolean.TRUE); hibernateTemplate.save(cert1); DetachedCriteria findCategoryT = DetachedCriteria.forClass(Category.class); findCategoryT.add(Restrictions.eq("name", "Category-1")); List getcategories = hibernateTemplate.findByCriteria(findCategoryT); Category getcat1 = (Category) getcategories.get(0); assertNotNull(getcat1); Set lins = getcat1.getLicenses(); Iterator linsIter = lins.iterator(); while (linsIter.hasNext()) { License lin = (License) linsIter.next(); System.out.println(lin); } DetachedCriteria findCertified = DetachedCriteria.forClass(Certified.class); findCertified.createAlias("category", "c"); findCertified.createAlias("license", "l"); findCertified.add(Restrictions.eq("c.name", "Category-1")); findCertified.add(Restrictions.eq("l.name", "License-2")); List getcertifies = hibernateTemplate.findByCriteria(findCertified); Certified getcert1 = (Certified) getcertifies.get(0); assertNotNull(getcert1); }
From source file:nl.b3p.viewer.admin.stripes.AttributeActionBean.java
License:Open Source License
public Resolution getGridData() throws JSONException { JSONArray jsonData = new JSONArray(); List<SimpleFeatureType> featureTypes = new ArrayList(); if (simpleFeatureTypeId != null && simpleFeatureTypeId != -1) { SimpleFeatureType sft = (SimpleFeatureType) Stripersist.getEntityManager().find(SimpleFeatureType.class, simpleFeatureTypeId);/*from www. j av a 2s.co m*/ if (sft != null) { featureTypes.add(sft); } } else if (featureSourceId != null && featureSourceId != -1) { FeatureSource fc = (FeatureSource) Stripersist.getEntityManager().find(FeatureSource.class, featureSourceId); featureTypes = fc.getFeatureTypes(); } String filterAlias = ""; String filterAttribuut = ""; String filterType = ""; /* * FILTERING: filter is delivered by frontend as JSON array [{property, value}] * for demo purposes the value is now returned, ofcourse here should the DB * query be built to filter the right records */ if (this.getFilter() != null) { for (int k = 0; k < this.getFilter().length(); k++) { JSONObject j = this.getFilter().getJSONObject(k); String property = j.getString("property"); String value = j.getString("value"); if (property.equals("alias")) { filterAlias = value; } if (property.equals("attribute")) { filterAttribuut = value; } if (property.equals("type")) { filterType = value; } } } Session sess = (Session) Stripersist.getEntityManager().getDelegate(); Criteria c = sess.createCriteria(AttributeDescriptor.class); /* Sorting is delivered by the frontend * as two variables: sort which holds the column name and dir which * holds the direction (ASC, DESC). */ if (sort != null && dir != null) { Order order = null; if (sort.equals("attribute")) { sort = "name"; } if (dir.equals("ASC")) { order = Order.asc(sort); } else { order = Order.desc(sort); } order.ignoreCase(); c.addOrder(order); } if (filterAlias != null && filterAlias.length() > 0) { Criterion aliasCrit = Restrictions.ilike("alias", filterAlias, MatchMode.ANYWHERE); c.add(aliasCrit); } if (filterAttribuut != null && filterAttribuut.length() > 0) { Criterion attribuutCrit = Restrictions.ilike("name", filterAttribuut, MatchMode.ANYWHERE); c.add(attribuutCrit); } if (filterType != null && filterType.length() > 0) { Criterion typeCrit = Restrictions.ilike("type", filterType, MatchMode.ANYWHERE); c.add(typeCrit); } if (featureTypes != null && featureTypes.size() > 0) { /* Criteria for the all attribute descriptor ids of the feature types * in featureTypes */ DetachedCriteria c2 = DetachedCriteria.forClass(SimpleFeatureType.class); Collection ftIds = new ArrayList<Long>(); for (SimpleFeatureType sft : featureTypes) { ftIds.add(sft.getId()); } c2.add(Restrictions.in("id", ftIds)); c2.createAlias("attributes", "attr"); c2.setProjection(Projections.property("attr.id")); c.add(org.hibernate.criterion.Property.forName("id").in(c2)); } int rowCount = c.list().size(); if (limit > 0) { c.setMaxResults(limit); } c.setFirstResult(start); List attributes = c.list(); for (Iterator it = attributes.iterator(); it.hasNext();) { AttributeDescriptor attr = (AttributeDescriptor) it.next(); JSONObject j = this.getGridRow(attr.getId().intValue(), attr.getAlias(), attr.getName(), attr.getType()); jsonData.put(j); } final JSONObject grid = new JSONObject(); grid.put("totalCount", rowCount); grid.put("gridrows", jsonData); return new StreamingResolution("application/json") { @Override public void stream(HttpServletResponse response) throws Exception { response.getWriter().print(grid.toString()); } }; }
From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java
License:Open Source License
public Resolution getAttributesList() throws JSONException { JSONArray jsonData = new JSONArray(); List<SimpleFeatureType> featureTypes = new ArrayList(); if (simpleFeatureTypeId != null && simpleFeatureTypeId != -1) { SimpleFeatureType sft = (SimpleFeatureType) Stripersist.getEntityManager().find(SimpleFeatureType.class, simpleFeatureTypeId);//ww w . ja va2 s. c o m if (sft != null) { featureTypes.add(sft); } } else { throw new IllegalArgumentException("No simpleFeatureType id provided"); } Session sess = (Session) Stripersist.getEntityManager().getDelegate(); Criteria c = sess.createCriteria(AttributeDescriptor.class); /* Criteria for the all attribute descriptor ids of the feature types * in featureTypes */ DetachedCriteria c2 = DetachedCriteria.forClass(SimpleFeatureType.class); Collection ftIds = new ArrayList<Long>(); for (SimpleFeatureType sft : featureTypes) { ftIds.add(sft.getId()); } c2.add(Restrictions.in("id", ftIds)); c2.createAlias("attributes", "attr"); c2.setProjection(Projections.property("attr.id")); c.add(org.hibernate.criterion.Property.forName("id").in(c2)); int rowCount = c.list().size(); List<AttributeDescriptor> attrs = c.list(); for (Iterator<AttributeDescriptor> it = attrs.iterator(); it.hasNext();) { AttributeDescriptor attr = it.next(); boolean indexChecked = false; boolean resultChecked = false; if (solrConfiguration != null) { for (AttributeDescriptor configAttribute : solrConfiguration.getIndexAttributes()) { if (configAttribute.getId() == attr.getId()) { indexChecked = true; break; } } for (AttributeDescriptor resultAttribute : solrConfiguration.getResultAttributes()) { if (resultAttribute.getId() == attr.getId()) { resultChecked = true; break; } } } JSONObject j = new JSONObject(); j.put("id", attr.getId().intValue()); j.put("alias", attr.getAlias()); j.put("attribute", attr.getName()); j.put("indexChecked", indexChecked); j.put("resultChecked", resultChecked); jsonData.put(j); } final JSONObject grid = new JSONObject(); grid.put("totalCount", rowCount); grid.put("gridrows", jsonData); return new StreamingResolution("application/json") { @Override public void stream(HttpServletResponse response) throws Exception { response.getWriter().print(grid.toString()); } }; }
From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java
License:Open Source License
/** * Retrieves an iterator over the compliance snapshots on the target date. * * @param targetDate/*from w w w. j a va 2 s . co m*/ * The date for which to retrieve compliance snapshots. If null, the current date will be used * instead. * * @param consumerUuids * A list of consumer UUIDs to use to filter the results. If provided, only compliances for * consumers in the list will be retrieved. * * @param ownerFilters * A list of owners to use to filter the results. If provided, only compliances for consumers * belonging to the specified owners (orgs) will be retrieved. * * @param statusFilters * A list of statuses to use to filter the results. If provided, only compliances with a status * matching the list will be retrieved. * * @param productNameFilters * A list of product names to use to filter compliances. If provided, only compliances for * consumers having installed the specified products will be retrieved. * * @param subscriptionSkuFilters * A list of subscription skus to use to filter compliances. If provided, only compliances for * the specified subscription skus will be retrieved. * * @param subscriptionNameFilters * A list of subscription names to use to filter compliances. If provided, only compliances for * the specified subscription names will be retrieved. * * @param attributeFilters * A map of entitlement attributes to use to filter compliances. If provided, only compliances * for entitlements having the specified values for the given attributes will be retrieved. * * @param pageRequest * A PageRequest instance containing paging information from the request. If null, no paging * will be performed. * * @return * A Page instance containing an iterator over the compliance snapshots for the target date and * the paging information for the query. */ @SuppressWarnings("checkstyle:indentation") public Page<Iterator<Compliance>> getSnapshotIterator(Date targetDate, List<String> consumerUuids, List<String> ownerFilters, List<String> statusFilters, List<String> productNameFilters, List<String> subscriptionSkuFilters, List<String> subscriptionNameFilters, Map<String, String> attributeFilters, PageRequest pageRequest) { Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>(); page.setPageRequest(pageRequest); DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class); subquery.createAlias("consumer", "c"); subquery.createAlias("c.consumerState", "state"); // https://hibernate.atlassian.net/browse/HHH-2776 if (consumerUuids != null && !consumerUuids.isEmpty()) { subquery.add(Restrictions.in("c.uuid", consumerUuids)); } Date toCheck = targetDate == null ? new Date() : targetDate; subquery.add( Restrictions.or(Restrictions.isNull("state.deleted"), Restrictions.gt("state.deleted", toCheck))); subquery.add(Restrictions.le("state.created", toCheck)); if (ownerFilters != null && !ownerFilters.isEmpty()) { subquery.createAlias("c.owner", "o"); subquery.add(Restrictions.in("o.key", ownerFilters)); } subquery.add(Restrictions.le("date", toCheck)); subquery.setProjection( Projections.projectionList().add(Projections.max("date")).add(Projections.groupProperty("c.uuid"))); Session session = this.currentSession(); Criteria query = session.createCriteria(Compliance.class, "comp").createAlias("comp.consumer", "cs") .add(Subqueries.propertiesIn(new String[] { "comp.date", "cs.uuid" }, subquery)) .setCacheMode(CacheMode.IGNORE).setReadOnly(true); if ((statusFilters != null && !statusFilters.isEmpty()) || (attributeFilters != null && attributeFilters.containsKey("management_enabled")) || (productNameFilters != null && !productNameFilters.isEmpty())) { query.createAlias("comp.status", "stat"); if (statusFilters != null && !statusFilters.isEmpty()) { query.add(Restrictions.in("stat.status", statusFilters)); } if (attributeFilters != null && attributeFilters.containsKey("management_enabled")) { boolean managementEnabledFilter = PropertyConverter .toBoolean(attributeFilters.get("management_enabled")); query.add(Restrictions.eq("stat.managementEnabled", managementEnabledFilter)); } if (productNameFilters != null && !productNameFilters.isEmpty()) { query.createAlias("stat.compliantProducts", "cprod", JoinType.LEFT_OUTER_JOIN) .createAlias("stat.partiallyCompliantProducts", "pcprod", JoinType.LEFT_OUTER_JOIN) .createAlias("stat.nonCompliantProducts", "ncprod", JoinType.LEFT_OUTER_JOIN); DetachedCriteria prodQuery = DetachedCriteria.forClass(Compliance.class, "comp2"); prodQuery.createAlias("comp2.consumer", "cons2"); prodQuery.createAlias("cons2.installedProducts", "installed"); prodQuery.add(Restrictions.and(Restrictions.in("installed.productName", productNameFilters), Restrictions.eqProperty("comp2.id", "comp.id"))); prodQuery.setProjection(Projections.property("installed.productId")); query.add(Restrictions.or(Property.forName("cprod.productId").in(prodQuery), Property.forName("pcprod.productId").in(prodQuery), Property.forName("ncprod.productId").in(prodQuery))); } } // Add subscription filters, if necessary if ((subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) || (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty())) { // Impl note: We have to be very careful with alias names, as Hibernate has a tendancy // to errorneously truncate "long" ones. Actual property/field names are safe, though. query.createAlias("comp.entitlements", "entsnap"); if (subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) { query.add(Restrictions.in("entsnap.productId", subscriptionSkuFilters)); } if (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty()) { query.add(Restrictions.in("entsnap.productName", subscriptionNameFilters)); } } if (pageRequest != null && pageRequest.isPaging()) { page.setMaxRecords(this.getRowCount(query)); query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage()); query.setMaxResults(pageRequest.getPerPage()); if (pageRequest.getSortBy() != null) { query.addOrder( pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy()) : Order.desc(pageRequest.getSortBy())); } } page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session, query.scroll(ScrollMode.FORWARD_ONLY), 0)); return page; }
From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java
License:Open Source License
/** * Retrieves an iterator over the compliance snapshots for the specified consumer. * * @param consumerUUID//from w ww . ja va2 s .c o m * The UUID for the consumer for which to retrieve compliance snapshots. * * @param startDate * The start date to use to filter snapshots retrieved. If specified, only snapshots occurring * after the start date, and the snapshot immediately preceding it, will be retrieved. * * @param endDate * The end date to use to filter snapshots retrieved. If specified, only snapshots occurring * before the end date will be retrieved. * * @param pageRequest * A PageRequest instance containing paging information from the request. If null, no paging * will be performed. * * @return * A Page instance containing an iterator over the snapshots for the specified consumer, and * the paging information for the query. */ @SuppressWarnings("checkstyle:indentation") public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate, Date endDate, PageRequest pageRequest) { Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>(); page.setPageRequest(pageRequest); Session session = this.currentSession(); Criteria query = session.createCriteria(Compliance.class, "comp1"); query.createAlias("comp1.consumer", "cons1"); query.add(Restrictions.eq("cons1.uuid", consumerUUID)); if (startDate != null) { DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2"); subquery.createAlias("comp2.consumer", "cons2"); subquery.createAlias("cons2.consumerState", "state2"); subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"), Restrictions.gt("state2.deleted", startDate))); subquery.add(Restrictions.lt("state2.created", startDate)); subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid")); subquery.add(Restrictions.lt("comp2.date", startDate)); subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date"))); query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate)) .add(Subqueries.propertyEq("comp1.date", subquery))); } if (endDate != null) { query.add(Restrictions.le("comp1.date", endDate)); } query.setCacheMode(CacheMode.IGNORE); query.setReadOnly(true); if (pageRequest != null && pageRequest.isPaging()) { page.setMaxRecords(this.getRowCount(query)); query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage()); query.setMaxResults(pageRequest.getPerPage()); if (pageRequest.getSortBy() != null) { query.addOrder( pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy()) : Order.desc(pageRequest.getSortBy())); } } page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session, query.scroll(ScrollMode.FORWARD_ONLY), 0)); return page; }