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

How to use
uniqueResult
method
in
org.hibernate.Criteria

Best Java code snippets using org.hibernate.Criteria.uniqueResult (Showing top 20 results out of 1,251)

Refine searchRefine arrow

  • Restrictions.eq
  • Criteria.add
  • Session.createCriteria
  • Criteria.setProjection
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: stackoverflow.com

 Criteria crit = session.createCriteria(Person.class);
crit.add( Restrictions.isNotNull("birthDate"));
crit.add( Restrictions.eq("isStudent", true));
crit.setProjection(Projections.rowCount());
Integer count = (Integer)crit.uniqueResult();
origin: gocd/gocd

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

@Test
public void shouldNotRetrieveSubSubSubEntityWithCriteria() {
  session = openSession();
  try {
    SubSubSubEntity loaded = (SubSubSubEntity) session.createCriteria( SubSubSubEntity.class )
        .add( Restrictions.idEq( subSubEntityId ) )
        .uniqueResult();
    assertNull( loaded );
  }
  finally {
    session.close();
  }
}
origin: hibernate/hibernate-orm

c = ( Contract ) s.createCriteria( Contract.class ).uniqueResult();
assertEquals( 0, c.getParties().size() );
party = ( Party ) s.createCriteria( Party.class ).uniqueResult();
assertNull( party );
s.delete( c );
assertEquals( Long.valueOf( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( Long.valueOf( 0 ), s.createCriteria(Party.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
origin: hibernate/hibernate-orm

@Test
public void testCriteriaCollection() throws Exception {
  Session s = openSession();
  s.beginTransaction();
  Baz bb = (Baz) s.createCriteria(Baz.class).uniqueResult();
  assertTrue( bb == null );
  Baz baz = new Baz();
  s.save( baz );
  s.getTransaction().commit();
  s.close();
  s = openSession();
  s.beginTransaction();
  Baz b = (Baz) s.createCriteria(Baz.class).uniqueResult();
  assertTrue( Hibernate.isInitialized( b.getTopGlarchez() ) );
  assertTrue( b.getTopGlarchez().size() == 0 );
  s.delete( b );
  s.getTransaction().commit();
  s.close();
}
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: kaaproject/kaa

protected T findOneByCriterion(Criterion criterion) {
 String className = getSimpleClassName();
 LOG.trace("Searching {} entity by criterion [{}] ", className, criterion);
 Criteria criteria = getCriteria();
 criteria.add(criterion);
 return (T) criteria.uniqueResult();
}
origin: BroadleafCommerce/BroadleafCommerce

@Override
public Long countContentItems(Criteria c) {
  c.setProjection(Projections.rowCount());
  return (Long) c.uniqueResult();
}
origin: kaaproject/kaa

@Override
public boolean validateApplicationEventFamilyMap(String appId, String ecfId, int version) {
 LOG.debug("Validating application event family map by application id [{}], ecf id [{}], "
      + "version [{}]", appId, ecfId, version);
 Criteria criteria = getCriteria();
 criteria.createAlias(APPLICATION_PROPERTY, APPLICATION_ALIAS);
 criteria.createAlias(ECF_PROPERTY, ECF_ALIAS);
 criteria.add(Restrictions.and(
   Restrictions.eq(APPLICATION_REFERENCE, Long.valueOf(appId)),
   Restrictions.eq(ECF_REFERENCE, Long.valueOf(ecfId)),
   Restrictions.eq(VERSION_PROPERTY, version)));
 Long count = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
 boolean result = count != null ? count == 0 : false;
 LOG.debug("[{},{},{}] Validation result: {}.", appId, ecfId, version, result);
 return result;
}
origin: hibernate/hibernate-orm

@Test
public void shouldRetrieveSubSubEntityWithCriteria() {
  session = openSession();
  try {
    SubSubEntity loaded = (SubSubEntity) session.createCriteria( SubSubEntity.class )
        .add( Restrictions.idEq( subSubEntityId ) )
        .uniqueResult();
    assertNotNull( loaded );
  }
  finally {
    session.close();
  }
}
origin: hibernate/hibernate-orm

@Test
public void testSaveOrUpdateManaged() {
  Session s = openSession();
  Transaction tx = s.beginTransaction();
  NumberedNode root = new NumberedNode( "root" );
  s.saveOrUpdate( root );
  tx.commit();
  tx = s.beginTransaction();
  NumberedNode child = new NumberedNode( "child" );
  root.addChild( child );
  s.saveOrUpdate( root );
  assertFalse( s.contains( child ) );
  s.flush();
  assertTrue( s.contains( child ) );
  tx.commit();
  assertTrue( root.getChildren().contains( child ) );
  assertEquals( root.getChildren().size(), 1 );
  tx = s.beginTransaction();
  assertEquals(
      Long.valueOf( 2 ),
      s.createCriteria( NumberedNode.class )
          .setProjection( Projections.rowCount() )
          .uniqueResult()
  );
  s.delete( root );
  s.delete( child );
  tx.commit();
  s.close();
}
origin: kaaproject/kaa

/**
 * Find user by password reset hash.
 *
 * @param passwordResetHash the password reset hash
 * @return user
 */
public User findByPasswordResetHash(String passwordResetHash) {
 Criteria criteria = getCriteria();
 criteria.add(Restrictions.eq(PASSWORD_RESET_HASH_PROPERTY, passwordResetHash));
 return (User) criteria.uniqueResult();
}
origin: hibernate/hibernate-orm

@Test
public void testLegacyCriteriaAliasSpecific() {
  // open a session, begin a transaction and lock row
  doInHibernate( this::sessionFactory, session -> {
    A it = (A) session.createCriteria( A.class )
        .setLockMode( "this", LockMode.PESSIMISTIC_WRITE )
        .uniqueResult();
    // make sure we got it
    assertNotNull( it );
    // that initial transaction is still active and so the lock should still be held.
    // Lets open another session/transaction and verify that we cannot update the row
    nowAttemptToUpdateRow();
  } );
}
origin: kaaproject/kaa

criteria.createAlias(ENDPOINT_GROUP_PROPERTY, ENDPOINT_GROUP_ALIAS);
Criterion crit = Restrictions.and(
  Restrictions.eq(ENDPOINT_GROUP_REFERENCE, Long.valueOf(groupId)),
  buildEqIdCriterion(ENDPOINT_PROFILE_SCHEMA_REFERENCE, endpointProfileSchemaId),
  buildEqIdCriterion(SERVER_PROFILE_SCHEMA_REFERENCE, serverProfileSchemaId),
  Restrictions.eq(STATUS_PROPERTY, UpdateStatus.DEPRECATED));
filter = (ProfileFilter) criteria.add(crit).addOrder(Order.desc(SEQUENCE_NUMBER_PROPERTY))
    .setMaxResults(FIRST).uniqueResult();
origin: stackoverflow.com

Criteria criteria=session.createCriteria(Student.class);
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED));
   criteria.setProjection(Projections.rowCount())
 Long resultCount = (Long)criteria.uniqueResult();
origin: kaaproject/kaa

protected T findOneByCriterionWithLock(Criterion criterion, LockMode lockMode) {
 String className = getSimpleClassName();
 LOG.trace("Searching {} entity by criterion [{}] ", className, criterion);
 Criteria criteria = getCriteria();
 criteria.setLockMode(lockMode);
 criteria.add(criterion);
 return (T) criteria.uniqueResult();
}
origin: gocd/gocd

public long enabledUserCount() {
  Long value = (Long) goCache.get(ENABLED_USER_COUNT_CACHE_KEY);
  if (value != null) {
    return value;
  }
  synchronized (ENABLED_USER_COUNT_CACHE_KEY) {
    value = (Long) goCache.get(ENABLED_USER_COUNT_CACHE_KEY);
    if (value == null) {
      value = hibernateTemplate().execute(session -> (Long) session.createCriteria(User.class).add(Restrictions.eq("enabled", true)).setProjection(Projections.rowCount()).setCacheable(true).uniqueResult());
      goCache.put(ENABLED_USER_COUNT_CACHE_KEY, value);
    }
    return value;
  }
}
origin: hibernate/hibernate-orm

@Test
public void testNaturalIdCriteria() {
  Session s = openSession();
  s.beginTransaction();
  Account u = new Account(new AccountId(1), "testAcct" );
  s.persist( u );
  s.getTransaction().commit();
  s.close();
  s = openSession();
  s.beginTransaction();
  u = ( Account ) s.createCriteria( Account.class )
      .add( Restrictions.naturalId().set( "shortCode", "testAcct" ) )
      .setCacheable( true )
      .uniqueResult();
  assertNotNull( u );
  s.getTransaction().commit();
  s.close();
  s = openSession();
  s.beginTransaction();
  s.createQuery( "delete Account" ).executeUpdate();
  s.getTransaction().commit();
  s.close();
}
origin: hibernate/hibernate-orm

@Test
public void testCreateWithNonEmptyOneToManyCollectionOfNew() {
  clearCounts();
  Contract c = new Contract( null, "gail", "phone");
  c.addParty( new Party( "party" ) );
  Session s = openSession();
  Transaction t = s.beginTransaction();
  s.persist(c);
  t.commit();
  s.close();
  assertInsertCount( 2 );
  assertUpdateCount( 0 );
  clearCounts();
  s = openSession();
  t = s.beginTransaction();
  c = (Contract) s.createCriteria( Contract.class ).uniqueResult();
  assertEquals( 1, c.getParties().size() );
  Party party = ( Party ) c.getParties().iterator().next();
  assertEquals( "party", party.getName() );
  if ( isContractPartiesBidirectional ) {
    assertSame( c, party.getContract() );
  }
  s.delete(c);
  assertEquals( Long.valueOf( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
  assertEquals( Long.valueOf( 0 ), s.createCriteria( Party.class ).setProjection( Projections.rowCount() ).uniqueResult() );
  t.commit();
  s.close();
  assertUpdateCount( 0 );
  assertDeleteCount( 2 );
}
org.hibernateCriteriauniqueResult

Javadoc

Convenience method to return a single instance that matches the query, or null if the query returns no results.

Popular methods of Criteria

  • list
    Get the results.
  • add
    Add a Criterion to constrain the results to be retrieved.
  • 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
  • setFetchSize
    Set a fetch size for the underlying JDBC query.
  • setCacheable,
  • setFetchSize,
  • scroll,
  • setLockMode,
  • setReadOnly,
  • setCacheRegion,
  • setTimeout,
  • setCacheMode,
  • setFlushMode

Popular in Java

  • Reading from database using SQL prepared statement
  • scheduleAtFixedRate (ScheduledExecutorService)
  • setRequestProperty (URLConnection)
  • setContentView (Activity)
  • Table (com.google.common.collect)
    A collection that associates an ordered pair of keys, called a row key and a column key, with a sing
  • BufferedReader (java.io)
    Wraps an existing Reader and buffers the input. Expensive interaction with the underlying reader is
  • InputStream (java.io)
    A readable source of bytes.Most clients will use input streams that read data from the file system (
  • Date (java.util)
    A specific moment in time, with millisecond precision. Values typically come from System#currentTime
  • CountDownLatch (java.util.concurrent)
    A synchronization aid that allows one or more threads to wait until a set of operations being perfor
  • Response (javax.ws.rs.core)
    Defines the contract between a returned instance and the runtime when an application needs to provid
  • Best IntelliJ 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