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

x33g5p2x  于2022-01-28 转载在 其他  
字(8.4k)|赞(0)|评价(0)|浏览(305)

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

Query.uniqueResult介绍

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

代码示例

代码示例来源:origin: hibernate/hibernate-orm

default R getSingleResult() {
  return uniqueResult();
}

代码示例来源:origin: dropwizard/dropwizard

/**
 * Convenience method to return a single instance that matches the query, or null if the query
 * returns no results.
 *
 * @param query the query to run
 * @return the single result or {@code null}
 * @throws HibernateException if there is more than one matching result
 * @see Query#uniqueResult()
 */
protected E uniqueResult(Query<E> query) throws HibernateException {
  return requireNonNull(query).uniqueResult();
}

代码示例来源:origin: hibernate/hibernate-orm

private void assertCount(long expected){
  long count = (Long) session.createQuery("select count(h) from Human h").uniqueResult();	
  Assert.assertEquals(expected, count);
}

代码示例来源:origin: hibernate/hibernate-orm

private <T> T getDerivedClassById(Employee e, Session s, Class<T> clazz) {
  return clazz.cast( s.createQuery( "from " + clazz.getName() + " d where d.emp.empId = :empId" )
          .setParameter( "empId", e.empId ).uniqueResult() );
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testJpqlBooleanLiteral() {
  Session session = openSession();
  session.getTransaction().begin();
  assertNotNull( session.createQuery( "from Employee e where e.active = true" ).uniqueResult() );
  assertNull( session.createQuery( "from Employee e where e.active = false" ).uniqueResult() );
  session.getTransaction().commit();
  session.close();
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testFilter() {
  try (Session session = openSession()) {
    Assert.assertEquals(
        Long.valueOf( 4 ),
        session.createQuery( "select count(u) from User u" ).uniqueResult()
    );
    session.enableFilter( "ageFilter" ).setParameter( "age", 24 );
    Assert.assertEquals(
        Long.valueOf( 2 ),
        session.createQuery( "select count(u) from User u" ).uniqueResult()
    );
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testJpqlFloatLiteral() {
  Session session = openSession();
  session.getTransaction().begin();
  Employee jDoe = (Employee) session.createQuery( "from Employee e where e.salary = " + SALARY + "f" ).uniqueResult();
  assertNotNull( jDoe );
  session.getTransaction().commit();
  session.close();
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testQueryUsingLockOptions() {
  // todo : need an association here to make sure the alias-specific lock modes are applied correctly
  doInHibernate( this::sessionFactory, session -> {
    session.createQuery( "from A a" )
        .setLockOptions( new LockOptions( LockMode.PESSIMISTIC_WRITE ) )
        .uniqueResult();
    session.createQuery( "from A a" )
        .setLockOptions( new LockOptions().setAliasSpecificLockMode( "a", LockMode.PESSIMISTIC_WRITE ) )
        .uniqueResult();
  } );
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void shouldRetrieveSubSubEntityWithHQL() {
  session = openSession();
  try {
    SubSubEntity loaded = (SubSubEntity) session.createQuery(
        "select se from SubSubEntity se where se.id = :id" )
        .setLong( "id", subSubEntityId )
        .uniqueResult();
    assertNotNull( loaded );
  }
  finally {
    session.close();
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void shouldNotRetrieveSubSubSubEntityWithHQL() {
  session = openSession();
  try {
    SubSubSubEntity loaded = (SubSubSubEntity) session.createQuery(
        "select se from SubSubSubEntity se where se.id = :id" )
        .setLong( "id", subSubEntityId )
        .uniqueResult();
    assertNull( loaded );
  }
  finally {
    session.close();
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
@TestForIssue(jiraKey = "HHH-13084")
public void testHql() {
  doInHibernate( this::sessionFactory, session -> {
    assertEquals( 1, session.createQuery( "from Person p where p.id is null", Person.class ).list().size() );
    assertEquals( 2, session.createQuery( "from Person p where p.id is not null", Person.class ).list().size() );
    assertEquals( 3L, session.createQuery( "select count( p ) from Person p" ).uniqueResult() );
  } );
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
@TestForIssue(jiraKey = "HHH-13084")
public void testHql() {
  doInHibernate( this::sessionFactory, session -> {
    assertEquals( 2, session.createQuery( "from Person p where p.id = 0", Person.class ).list().size() );
    assertEquals( 3L, session.createQuery( "select count( p ) from Person p" ).uniqueResult() );
  } );
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void test_hql_api_unique_result_example() {
  doInJPA( this::entityManagerFactory, entityManager -> {
    Session session = entityManager.unwrap( Session.class );
    //tag::hql-api-unique-result-example[]
    Person person = (Person) session.createQuery(
      "select p " +
      "from Person p " +
      "where p.name like :name" )
    .setParameter( "name", "J%" )
    .uniqueResult();
    //end::hql-api-unique-result-example[]
  });
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
@TestForIssue( jiraKey = "HHH-11957")
public void testSubstrWithoutStringUnits() {
  mostRecentStatementInspector.clear();
  doInHibernate(
      this::sessionFactory, session -> {
        String value = session.createQuery(
            "select substr( e.description, 21, 11 ) from AnEntity e",
            String.class
        ).uniqueResult();
        assertEquals( "description", value );
      }
  );
  assertTrue( mostRecentStatementInspector.mostRecentSql.contains( "substr(" ) );
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testManagedWithUninitializedAssociation() {
  // Delete the Parent
  doInHibernate( this::sessionFactory, s -> {
    Parent loadedParent = (Parent) s.createQuery( "SELECT p FROM Parent p WHERE name=:name" )
        .setParameter( "name", "PARENT" )
        .uniqueResult();
    checkInterceptor( loadedParent, false );
    assertFalse( Hibernate.isPropertyInitialized( loadedParent, "children" ) );
    s.delete( loadedParent );
  } );
  // If the lazy relation is not fetch on cascade there is a constraint violation on commit
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testQuery() {
  // open a session, begin a transaction and lock row
  doInHibernate( this::sessionFactory, session -> {
    A it = (A) session.createQuery( "from A a" )
        .setLockMode( "a", 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: hibernate/hibernate-orm

@Test(expected = TransactionRequiredException.class)
public void testFlushDisallowingOutOfTransactionUpdateOperations() throws Exception {
  allowUpdateOperationOutsideTransaction = "false";
  rebuildSessionFactory();
  prepareTest();
  try (Session s = openSession()) {
    final MyEntity entity = (MyEntity) s.createQuery( "from MyEntity e where e.name = :n" )
        .setParameter( "n", "entity" )
        .uniqueResult();
    assertThat( entity, not( nullValue() ) );
    entity.setName( "changed" );
    session.flush();
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Test(expected = TransactionRequiredException.class)
public void testFlushOutOfTransaction() throws Exception {
  allowUpdateOperationOutsideTransaction = "";
  rebuildSessionFactory();
  prepareTest();
  try (Session s = openSession()) {
    final MyEntity entity = (MyEntity) s.createQuery( "from MyEntity e where e.name = :n" )
        .setParameter( "n", "entity" )
        .uniqueResult();
    assertThat( entity, not( nullValue() ) );
    entity.setName( "changed" );
    session.flush();
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testFlushAllowingOutOfTransactionUpdateOperations() throws Exception {
  allowUpdateOperationOutsideTransaction = "true";
  rebuildSessionFactory();
  prepareTest();
  try (Session s = openSession()) {
    final MyEntity entity = (MyEntity) s.createQuery( "from MyEntity e where e.name = :n" )
        .setParameter( "n", "entity" )
        .uniqueResult();
    assertThat( entity, not( nullValue() ) );
    entity.setName( "changed" );
    session.flush();
  }
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
@TestForIssue( jiraKey = "HHH-9637")
public void testExplicitJoinAfterFetchJoins() {
  Session s = openSession();
  s.getTransaction().begin();
  Entity1 e1Queryied =
      (Entity1) s.createQuery(
          "select e1 from Entity1 e1 inner join fetch e1.entity2 e2 inner join fetch e2.entity3 inner join e1.entity2 e1Restrict where e1Restrict.value = 'entity2'" )
          .uniqueResult();
  assertEquals( "entity1", e1Queryied.getValue() );
  assertTrue( Hibernate.isInitialized( e1Queryied.getEntity2() ) );
  assertTrue( Hibernate.isInitialized( e1Queryied.getEntity2().getEntity3() ) );
  s.getTransaction().commit();
  s.close();
}

相关文章