org.hibernate.Criteria.uniqueResult()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(265)

本文整理了Java中org.hibernate.Criteria.uniqueResult()方法的一些代码示例,展示了Criteria.uniqueResult()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Criteria.uniqueResult()方法的具体详情如下:
包路径:org.hibernate.Criteria
类名称:Criteria
方法名:uniqueResult

Criteria.uniqueResult介绍

[英]Convenience method to return a single instance that matches the query, or null if the query returns no results.
[中]方法返回与查询匹配的单个实例,如果查询不返回结果,则返回null。

代码示例

代码示例来源: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 );
}

相关文章