Tabnine Logo
Criteria
Code IndexAdd Tabnine to your IDE (free)

How to use
Criteria
in
org.hibernate

Best Java code snippets using org.hibernate.Criteria (Showing top 20 results out of 2,340)

Refine searchRefine arrow

  • Restrictions
  • Session
  • SessionFactory
  • Order
  • Projections
  • Session
origin: gocd/gocd

public EnvironmentVariables load(final Long entityId, final EnvironmentVariableType type) {
  List<EnvironmentVariable> result = (List<EnvironmentVariable>) transactionTemplate.execute((TransactionCallback) transactionStatus -> {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(EnvironmentVariable.class).add(Restrictions.eq("entityId", entityId)).add(
        Restrictions.eq("entityType", type.toString())).addOrder(Order.asc("id"));
    criteria.setCacheable(true);
    return criteria.list();
  });
  return new EnvironmentVariables(result);
}
origin: kaaproject/kaa

@Override
public LogSchema findLatestLogSchemaByAppId(String applicationId) {
 LOG.debug("Searching latest log schema  by application id [{}]", applicationId);
 LogSchema logSchema = null;
 if (isNotBlank(applicationId)) {
  Criteria criteria = getCriteria();
  criteria.createAlias(APPLICATION_PROPERTY, APPLICATION_ALIAS);
  Criterion criterion = Restrictions.eq(APPLICATION_REFERENCE, Long.valueOf(applicationId));
  logSchema = (LogSchema) criteria.add(criterion).addOrder(Order.desc(VERSION_PROPERTY))
    .setMaxResults(FIRST).uniqueResult();
 }
 if (LOG.isTraceEnabled()) {
  LOG.trace("[{}] Search result: {}.", applicationId, logSchema);
 } else {
  LOG.debug("[{}] Search result: {}.", applicationId, logSchema != null);
 }
 return logSchema;
}
origin: hibernate/hibernate-orm

  protected Criteria getCriteria(Session s) {
    // should use PassThroughTransformer by default
    return s.createCriteria( Enrolment.class, "e" )
        .setProjection( Projections.property( "e.semester" ) )
        .addOrder( Order.asc( "e.studentNumber") );
  }
};
origin: gocd/gocd

  @Override
  public Object doInTransaction(TransactionStatus status) {
    PropertyProjection pipelineName = Projections.property("pipelineName");
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PipelineState.class).setProjection(pipelineName).add(
        Restrictions.eq("locked", true));
    criteria.setCacheable(false);
    List<String> list = criteria.list();
    return list;
  }
});
origin: gocd/gocd

  @Override
  public Object doInTransaction(TransactionStatus transactionStatus) {
    return sessionFactory.getCurrentSession()
        .createCriteria(PipelineState.class)
        .add(Restrictions.eq("pipelineName", pipelineName))
        .setCacheable(false).uniqueResult();
  }
});
origin: stackoverflow.com

Criteria criteria=session.createCriteria(Student.class);
  criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
  criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED));
  criteria.setMaxResults(10);
  criteria.setFirstResult((paginate.getStartIndex()-1)*10);
  List<Student> students = criteria.list();
 criteria.setProjection(null);
 criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
 Long resultCount = (Long)criteria.uniqueResult();
origin: hibernate/hibernate-orm

@TestForIssue(jiraKey = "HHH-4838")
@Test
public void testNaturalKeyLookupWithConstraint() {
  Session s = openSession();
  Transaction newTx = s.getTransaction();
  newTx.begin();
  A a1 = new A();
  a1.setName( "name1" );
  s.persist( a1 );
  newTx.commit();
  newTx = s.beginTransaction();
  getCriteria( s ).add( Restrictions.isNull( "singleD" ) ).uniqueResult(); // put query-result into cache
  A a2 = new A();
  a2.setName( "xxxxxx" );
  s.persist( a2 );
  newTx.commit();      // Invalidates space A in UpdateTimeStamps region
  newTx = s.beginTransaction();
  Assert.assertTrue( s.getSessionFactory().getStatistics().isStatisticsEnabled() );
  s.getSessionFactory().getStatistics().clear();
  // should not produce a hit in StandardQuery cache region because there is a constraint
  getCriteria( s ).add( Restrictions.isNull( "singleD" ) ).uniqueResult();
  Assert.assertEquals( 0, s.getSessionFactory().getStatistics().getQueryCacheHitCount() );
  s.createQuery( "delete from A" ).executeUpdate();
  newTx.commit();
  // Shutting down the application
  s.close();
}
origin: hibernate/hibernate-orm

  .add( Restrictions.eq( "integer", f.getInteger() ) )
  .add( Restrictions.eqProperty("integer", "integer") )
  .add( Restrictions.like( "string", f.getString().toUpperCase(Locale.ROOT) ).ignoreCase() )
  .add( Restrictions.in( "boolean", f.getBoolean(), f.getBoolean() ) )
  .setFetchMode("foo", FetchMode.JOIN)
  .setFetchMode("baz", FetchMode.SELECT)
  .setFetchMode("abstracts", FetchMode.JOIN)
  .list();
assertTrue( list.size() == 1 && list.get( 0 ) == f );
list = s.createCriteria(Foo.class).add(
  .add( Restrictions.isNotNull("boolean") )
  .list();
assertTrue( list.size() == 1 && list.get( 0 ) == f );
list = s.createCriteria(Foo.class).add(
  Example.create(example)
    .excludeZeroes()
  .list();
assertTrue(
    "Example API without like did not work correctly, size was " + list.size(),
list = s.createCriteria(Foo.class).add(
  Example.create(example)
    .excludeZeroes()
  .list();
origin: hibernate/hibernate-orm

@Test
public void testCriteriaRestrictionOnKeyManyToOne() {
  Session s = openSession();
  s.beginTransaction();
  s.createQuery( "from Order o where o.customer.name = 'Acme'" ).list();
  Criteria criteria = s.createCriteria( Order.class );
  criteria.createCriteria( "customer" ).add( Restrictions.eq( "name", "Acme" ) );
  criteria.list();
  s.getTransaction().commit();
  s.close();
}
origin: openmrs/openmrs-core

/**
 * @see org.openmrs.api.db.OpenmrsDataDAO#getAll(boolean, java.lang.Integer, java.lang.Integer)
 */
@Override
public List<T> getAll(boolean includeVoided, Integer firstResult, Integer maxResults) {
  Criteria crit = sessionFactory.getCurrentSession().createCriteria(mappedClass);
  
  if (!includeVoided) {
    crit.add(Restrictions.eq("voided", false));
  }
  crit.setFirstResult(firstResult);
  crit.setMaxResults(maxResults);
  
  return crit.list();
  
}

origin: BroadleafCommerce/BroadleafCommerce

@Override
public List<AssignedProductOptionDTO> findAssignedProductOptionsByProductId(Long productId) {
  Session session = em.unwrap(Session.class);
  Criteria criteria = session.createCriteria(SkuProductOptionValueXrefImpl.class);
  List dtoList = criteria
    .createAlias("sku", "sku")
    .createAlias("sku.product", "product")
    .createAlias("productOptionValue", "productOptionValue")
    .createAlias("productOptionValue.productOption", "productOption")
    .setProjection(Projections.distinct(
        Projections.projectionList()
        .add(Projections.property("product.id"), "productId")
        .add(Projections.property("productOption.attributeName"), "productOptionAttrName")
        .add(Projections.property("productOptionValue"), "productOptionValue")
        .add(Projections.property("sku"), "sku")
      )
    ).setResultTransformer(Transformers.aliasToBean(AssignedProductOptionDTO.class))
    .add(Restrictions.eq("product.id", productId))
    .addOrder(Order.asc("productOption.attributeName")).list();
  List<AssignedProductOptionDTO> results = new ArrayList<>();
  for (Object o : dtoList) {
    AssignedProductOptionDTO dto = (AssignedProductOptionDTO) o;
    if (dto.getSku().isActive()) {
      results.add(dto);
    }
  }
  return results;
}
origin: hibernate/hibernate-orm

protected Criteria getCriteria(Session s) throws Exception {
  return s.createCriteria( Student.class, "s" )
  .setProjection(
      Projections.projectionList()
          .add( Projections.sqlProjection( "555 as studentNumber", new String[]{ "studentNumber" }, new Type[] { StandardBasicTypes.LONG } ) )
          .add( Property.forName( "s.name" ).as( "name" ) )
  )
  .addOrder( Order.asc( "s.studentNumber" ) )
  .setResultTransformer( new AliasToBeanConstructorResultTransformer( getConstructor() ) );
}
private Constructor getConstructor() throws NoSuchMethodException {
origin: hibernate/hibernate-orm

Category category2 = new Category( 2, "Category2" );
Category category3 = new Category( 3, "Category3" );
session.persist( category1 );
session.persist( category2 );
session.persist( category3 );
session.flush();
session.persist( new Product2( 1, "Kit1", category1 ) );
List<Object[]> result = session.createCriteria( Category.class, "c" ).createAlias( "products", "p" )
    .setProjection(
        Projections.projectionList()
            .add( Projections.groupProperty( "c.id" ) )
            .add( Projections.countDistinct( "p.id" ) )
    .addOrder( Order.asc( "c.id" ) )
    .setFirstResult( 1 ).setMaxResults( 3 ).list();
origin: openmrs/openmrs-core

@SuppressWarnings("unchecked")
@Override
public List<Encounter> getEncountersNotAssignedToAnyVisit(Patient patient) throws DAOException {
  return sessionFactory.getCurrentSession().createCriteria(Encounter.class).add(Restrictions.eq("patient", patient))
      .add(Restrictions.isNull("visit")).add(Restrictions.eq("voided", false)).addOrder(
        Order.desc("encounterDatetime")).setMaxResults(100).list();
}

origin: iluwatar/java-design-patterns

 @Override
 public Spell findByName(String name) {
  Transaction tx = null;
  Spell result = null;
  try (Session session = getSessionFactory().openSession()) {
   tx = session.beginTransaction();
   Criteria criteria = session.createCriteria(persistentClass);
   criteria.add(Restrictions.eq("name", name));
   result = (Spell) criteria.uniqueResult();
   tx.commit();
  } catch (Exception e) {
   if (tx != null) {
    tx.rollback();
   }
   throw e;
  }
  return result;
 }
}
origin: hibernate/hibernate-orm

private EntityMapEnum assertFindCriteria(
    EntityMapEnum expected,
    String mapPath, Object param) {
  assertNotEquals( 0, expected.id );
  Session session = openNewSession();
  session.beginTransaction();
  EntityMapEnum found = (EntityMapEnum) session.createCriteria( EntityMapEnum.class )
      .createCriteria( mapPath, "m" )
      .add( Restrictions.eq( "indices", param ) )
      .uniqueResult();
  //find
  assetEntityMapEnumEquals( expected, found );
  session.getTransaction().commit();
  session.close();
  return found;
}
origin: hibernate/hibernate-orm

/**
 * Use a Criteria query - see FORGE-247
 */
public List listEventsWithCriteria() {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  List result = session.createCriteria(Event.class)
    .setCacheable(true)
    .list();
  session.getTransaction().commit();
  return result;
}
origin: hibernate/hibernate-orm

  @Test
  public void testEnablingJoinFetchProfileAgainstSelfReferentialAssociation() {
    Session s = openSession();
    s.beginTransaction();
    s.enableFetchProfile( Employee.FETCH_PROFILE_TREE );
    s.createCriteria( Employee.class )
        .add( Restrictions.isNull( "manager" ) )
        .list();
    s.getTransaction().commit();
    s.close();
  }
}
origin: openmrs/openmrs-core

/**
 * @see org.openmrs.api.db.FormDAO#getFormsByName(java.lang.String)
 */
@Override
@SuppressWarnings("unchecked")
public List<Form> getFormsByName(String name) throws DAOException {
  Criteria crit = sessionFactory.getCurrentSession().createCriteria(Form.class);
  
  crit.add(Restrictions.eq("name", name));
  crit.add(Restrictions.eq("retired", false));
  crit.addOrder(Order.desc("version"));
  
  return crit.list();
}

origin: hibernate/hibernate-orm

@Test
public void testCriteria() {
  Session session = openSession();
  session.beginTransaction();
  Criteria criteria = session.createCriteria( Door.class );
  criteria.setLockMode( LockMode.PESSIMISTIC_WRITE );
  criteria.setFirstResult( 2 );
  criteria.setMaxResults( 2 );
  @SuppressWarnings("unchecked") List<Door> results = criteria.list();
  assertEquals( 2, results.size() );
  for ( Door door : results ) {
    assertEquals( LockMode.PESSIMISTIC_WRITE, session.getCurrentLockMode( door ) );
  }
  session.getTransaction().commit();
  session.close();
}
org.hibernateCriteria

Javadoc

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

The Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on Restrictions. eg.
 
List cats = session.createCriteria(Cat.class) 
.add( Restrictions.like("name", "Iz%") ) 
.add( Restrictions.gt( "weight", new Float(minWeight) ) ) 
.addOrder( Order.asc("age") ) 
.list(); 
You may navigate associations using createAlias() or createCriteria().
 
List cats = session.createCriteria(Cat.class) 
.createCriteria("kittens") 
.add( Restrictions.like("name", "Iz%") ) 
.list(); 
 
List cats = session.createCriteria(Cat.class) 
.createAlias("kittens", "kit") 
.add( Restrictions.like("kit.name", "Iz%") ) 
.list(); 
You may specify projection and aggregation using Projection instances obtained via the factory methods on Projections.
 
List cats = session.createCriteria(Cat.class) 
.setProjection( Projections.projectionList() 
.add( Projections.rowCount() ) 
.add( Projections.avg("weight") ) 
.add( Projections.max("weight") ) 
.add( Projections.min("weight") ) 
.add( Projections.groupProperty("color") ) 
) 
.addOrder( Order.asc("color") ) 
.list(); 

Most used methods

  • list
    Get the results.
  • add
    Add a Criterion to constrain the results to be retrieved.
  • uniqueResult
    Convenience method to return a single instance that matches the query, or null if the query returns
  • addOrder
    Add an Order to the result set.
  • setProjection
    Used to specify that the query results will be a projection (scalar in nature). Implicitly specifies
  • setMaxResults
    Set a limit upon the number of objects to be retrieved.
  • setFirstResult
    Set the first result to be retrieved.
  • setResultTransformer
    Set a strategy for handling the query results. This determines the "shape" of the query result.
  • createAlias
    Join an association using the specified join-type, assigning an alias to the joined association. The
  • createCriteria
    Create a new Criteria, "rooted" at the associated entity, using the specified join type.
  • setFetchMode
    Specify an association fetching strategy for an association or a collection of values.
  • setCacheable
    Enable caching of this query result, provided query caching is enabled for the underlying session fa
  • setFetchMode,
  • setCacheable,
  • setFetchSize,
  • scroll,
  • setLockMode,
  • setReadOnly,
  • setCacheRegion,
  • setTimeout,
  • setCacheMode,
  • setFlushMode

Popular in Java

  • Reading from database using SQL prepared statement
  • notifyDataSetChanged (ArrayAdapter)
  • putExtra (Intent)
  • onRequestPermissionsResult (Fragment)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • FileReader (java.io)
    A specialized Reader that reads from a file in the file system. All read requests made by calling me
  • Timer (java.util)
    Timers schedule one-shot or recurring TimerTask for execution. Prefer java.util.concurrent.Scheduled
  • Vector (java.util)
    Vector is an implementation of List, backed by an array and synchronized. All optional operations in
  • AtomicInteger (java.util.concurrent.atomic)
    An int value that may be updated atomically. See the java.util.concurrent.atomic package specificati
  • JComboBox (javax.swing)
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now