org.hibernate.Query类的使用及代码示例

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

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

Query介绍

[英]Represents an HQL/JPQL query or a compiled Criteria query
[中]表示HQL/JPQL查询或编译条件查询

代码示例

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

/**
 * Call setEntity() on a cacheable query - see FORGE-265
 */
public List listEventsOfOrganizer(Person organizer) {
  Session session = sessionFactory.getCurrentSession();
  session.beginTransaction();
  Query query = session.createQuery("from Event ev where ev.organizer = :organizer");
  query.setCacheable(true);
  query.setEntity("organizer", organizer);
  List result = query.list();
  session.getTransaction().commit();
  return result;
}

代码示例来源:origin: citerus/dddsample-core

@Override
public HandlingHistory lookupHandlingHistoryOfCargo(final TrackingId trackingId) {
 return new HandlingHistory(getSession().createQuery(
     "from HandlingEvent where cargo.trackingId = :tid").
     setParameter("tid", trackingId).
     list()
 );
}

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

Modification findLatestModification(final MaterialInstance expandedInstance) {
  Modifications modifications = cachedModifications(expandedInstance);
  if (modifications != null && !modifications.isEmpty()) {
    return modifications.get(0);
  }
  String cacheKey = latestMaterialModificationsKey(expandedInstance);
  synchronized (cacheKey) {
    Modification modification = (Modification) getHibernateTemplate().execute((HibernateCallback) session -> {
      Query query = session.createQuery("FROM Modification WHERE materialId = ? ORDER BY id DESC");
      query.setMaxResults(1);
      query.setLong(0, expandedInstance.getId());
      return query.uniqueResult();
    });
    goCache.put(cacheKey, new Modifications(modification));
    return modification;
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Apply the given name parameter to the given Query object.
 * @param queryObject the Query object
 * @param paramName the name of the parameter
 * @param value the value of the parameter
 * @throws HibernateException if thrown by the Query object
 */
@Deprecated
@SuppressWarnings({"rawtypes", "deprecation"})
protected void applyNamedParameterToQuery(org.hibernate.Query queryObject, String paramName, Object value)
    throws HibernateException {
  if (value instanceof Collection) {
    queryObject.setParameterList(paramName, (Collection<?>) value);
  }
  else if (value instanceof Object[]) {
    queryObject.setParameterList(paramName, (Object[]) value);
  }
  else {
    queryObject.setParameter(paramName, value);
  }
}

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

@Override
public boolean deleteUsers(List<String> userNames) {
  return (Boolean) transactionTemplate.execute((TransactionCallback) status -> {
    String queryString = "delete from User where name in (:userNames)";
    Query query = sessionFactory.getCurrentSession().createQuery(queryString);
    query.setParameterList("userNames", userNames);
    query.executeUpdate();
    return Boolean.TRUE;
  });
}

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

@Override
public List<Plugin> getAllPlugins() {
  return (List<Plugin>) transactionTemplate.execute((TransactionCallback) transactionStatus -> {
    Query query = sessionFactory.getCurrentSession().createQuery("FROM " + Plugin.class.getSimpleName());
    query.setCacheable(true);
    return query.list();
  });
}

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

q.setMaxResults( 10 );
assertTrue( q.list().size()==3 );
q = s.createQuery("from Simple s");
q.setMaxResults( 1 );
assertTrue( q.list().size()==1 );
q = s.createQuery("from Simple s");
assertTrue( q.list().size() == 3 );
q = s.createQuery("from Simple s where s.name = ?");
q.setString( 0, "Simple 1" );
assertTrue( q.list().size()==1 );
q = s.createQuery("from Simple s where s.name = ? and upper(s.name) = ?");
q.setString(1, "SIMPLE 1");
q.setString( 0, "Simple 1" );
q.setFirstResult(0);
assertTrue( q.iterate().hasNext() );
q = s.createQuery("from Simple s where s.name = :foo and upper(s.name) = :bar or s.count=:count or s.count=:count + 1");
q.setParameter( "bar", "SIMPLE 1" );
q.setString( "foo", "Simple 1" );
q.setInteger("count", 69);
q.setFirstResult(0);
assertTrue( q.iterate().hasNext() );
q = s.createQuery("select s.id from Simple s");
q.setFirstResult(1);
q.setMaxResults( 2 );
iter = q.iterate();
int i=0;
while ( iter.hasNext() ) {
q.setParameter("s", simple);

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

q.setCacheRegion("foo");
q.setCacheable(true);
q.setString(0, "Simple 1");
assertTrue( q.list().size()==1 );
assertTrue( q.list().size()==1 );
assertTrue( q.list().size()==1 );
q = s.createQuery("from Simple s where s.name=:name");
q.setCacheRegion("foo");
q.setCacheable(true);
q.setString("name", "Simple 1");
assertTrue( q.list().size()==1 );
simple = (Simple) q.list().get(0);
q.setString("name", "Simple 2");
assertTrue( q.list().size()==0 );
assertTrue( q.list().size()==0 );
simple.setName("Simple 2");
assertTrue( q.list().size()==1 );
assertTrue( q.list().size()==1 );
t.commit();
t.commit();
q.setCacheRegion("foo");
q.setCacheable(true);
q.setString(0, "Simple 1");
assertTrue( q.list().size()==0 );
assertTrue( q.list().size()==0 );

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

@Test
public void test2ndLevelSubClass() throws Exception {
  Session s = openSession();
  Transaction tx = s.beginTransaction();
  A320b a = new A320b();
  a.setJavaEmbeddedVersion( "Elephant" );
  a.setNbrOfSeats( 300 );
  s.persist( a );
  tx.commit();
  s.close();
  s = openSession();
  tx = s.beginTransaction();
  Query q = s.createQuery( "from " + A320.class.getName() + " as a where a.javaEmbeddedVersion = :version" );
  q.setString( "version", "Elephant" );
  List a320s = q.list();
  assertNotNull( a320s );
  assertEquals( 1, a320s.size() );
  tx.commit();
  s.close();
}

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

@Test
public void testDeclarativeMix() throws Exception {
  Configuration cfg = new Configuration();
  cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
  cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
  SessionFactory sf = cfg.buildSessionFactory();
  assertNotNull( sf );
  Session s = sf.openSession();
  Transaction tx = s.beginTransaction();
  Query q = s.createQuery( "from Boat" );
  assertEquals( 0, q.list().size() );
  q = s.createQuery( "from Plane" );
  assertEquals( 0, q.list().size() );
  tx.commit();
  s.close();
  sf.close();
}
 @Test

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

@Test
public void testDeleteSingleValue() {
  final String name = "Name";
  final String lastName = "LastName";
  final String fullName = name + " " + lastName;
  final FromEntity fromEntity = createFrom( name, lastName );
  final DestinationEntity destinationEntity = createDestination( fromEntity, fullName );
  Session session = openSession();
  session.getTransaction().begin();
  Query delete = session.getNamedQuery( "DestinationEntity.delete" );
  delete.setParameterList( "ids", Collections.singletonList( destinationEntity.id ) );
  int executeUpdate = delete.executeUpdate();
  assertEquals( 1, executeUpdate );
  session.getTransaction().commit();
  session.close();
  session = openSession();
  DestinationEntity get = (DestinationEntity) session.get( DestinationEntity.class, destinationEntity.id );
  session.close();
  assertNull( get );
}

代码示例来源:origin: org.jbpm/jbpm-bam

@SuppressWarnings("unchecked")
public static List<NodeInstanceLog> findNodeInstances(long processInstanceId, String nodeId) {
  Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();
  List<NodeInstanceLog> result = session.createQuery(
    "from NodeInstanceLog as log where log.processInstanceId = ? and log.nodeId = ?")
      .setLong(0, processInstanceId)
      .setString(1, nodeId).list();
  session.getTransaction().commit();
  return result;
}

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

@Test
public void testCharLengthFunction() {
  final Session s = openSession();
  s.getTransaction().begin();
  Query query = session.createQuery( "select char_length('123456') from Product" );
  assertEquals(6, ((Number) query.uniqueResult()).intValue());
  s.getTransaction().commit();
  s.close();
}

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

list = q.list();
if ( !(getDialect() instanceof SAPDBDialect) ) assertTrue( list.size()==2 );
nameList.add( "Bar" );
nameList.add( "Bar Two" );
q.setParameterList( "nameList", nameList );
q.setParameter( "stringVal", "a string" );
list = q.list();
if ( !(getDialect() instanceof SAPDBDialect) ) assertTrue( list.size()==2 );
  q.setParameterList("nameList", (Collection)null);
  fail("Should throw a QueryException when passing a null!");
Object result = q.uniqueResult();
q.setString( "name", "Bar%" );
list = q.list();
assertTrue( list.size()==1 );
q.setInteger( "valueX", bar.getX() + 1 );
list = q.list();
assertTrue( ((Bar) list.get( 0 )).getX() == bar.getX() );
q.setInteger( "valueX", bar2.getX() + 1 );
list = q.list();
assertTrue( ((Bar)list.get(0)).getX() == bar2.getX());
txn.commit();

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

public SyntaxChecker checkList() {
  Session s = openSession();
  s.beginTransaction();
  Query query = s.createQuery( hql );
  preparer.prepare( query );
  query.list();
  s.getTransaction().commit();
  s.close();
  return this;
}

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

assertFalse( s.isDefaultReadOnly() );
Transaction t = s.beginTransaction();
s.save( cOrig );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
t.commit();
    .setMaxResults( 1 )
    .list();
    .setMaxResults( 1 )
    .list();
    .setMaxResults( 1 )
    .list();
t.commit();
t.commit();

代码示例来源:origin: org.ikasan/ikasan-connector-basefiletransfer

Session session = this.sessionFactory.openSession();
try
  Query query = session.createQuery(hibernateQuery.toString());
  query.setParameter(CLIENT_ID, clientId);
  query.setParameter(CREATED_DATE_TIME, cal.getTime().getTime());
  query.setMaxResults(maxRows);
  fileFilters = query.list();
  if (fileFilters != null)
      session.delete(fileFilter);
      session.flush();
  sb.append(hibernateQuery.toString());
  sb.append("].");
  logger.error(sb.toString() + " " + e.getMessage(), e);
  throw e;

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

@Test
public void testPSCache() throws Exception {
  Session s = openSession();
  Transaction txn = s.beginTransaction();
  for ( int i=0; i<10; i++ ) s.save( new Foo() );
  Query q = s.createQuery("from Foo");
  q.setMaxResults(2);
  q.setFirstResult(5);
  assertTrue( q.list().size()==2 );
  q = s.createQuery("from Foo");
  assertTrue( q.list().size()==10 );
  assertTrue( q.list().size()==10 );
  q.setMaxResults(3);
  q.setFirstResult(3);
  assertTrue( q.list().size()==3 );
  q = s.createQuery("from Foo");
  assertTrue( q.list().size()==10 );
  txn.commit();
  s.close();
  s = openSession();
  txn = s.beginTransaction();
  q = s.createQuery("from Foo");
  assertTrue( q.list().size()==10 );
  q.setMaxResults(5);
  assertTrue( q.list().size()==5 );
  doDelete( s, "from Foo" );
  txn.commit();
  s.close();
}

代码示例来源:origin: sakaiproject/sakai

public List<StudentGradingSummaryData> getStudentGradingSummaryData(final Long publishedAssessmentId, final String agentIdString) {
  final HibernateCallback<List<StudentGradingSummaryData>> hcb = session -> {
    Query q = session.createQuery(
        "select s " +
            "from StudentGradingSummaryData s " +
            "where s.publishedAssessmentId = :id and s.agentId = :agent");
    q.setLong("id", publishedAssessmentId);
    q.setString("agent", agentIdString);
    return q.list();
  };
  return getHibernateTemplate().execute(hcb);
}

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

@Test
public void testHql() {
  Session session = openSession();
  session.beginTransaction();
  Query qry = session.createQuery( "from Door" );
  qry.getLockOptions().setLockMode( LockMode.PESSIMISTIC_WRITE );
  qry.setFirstResult( 2 );
  qry.setMaxResults( 2 );
  @SuppressWarnings("unchecked") List<Door> results = qry.list();
  assertEquals( 2, results.size() );
  for ( Door door : results ) {
    assertEquals( LockMode.PESSIMISTIC_WRITE, session.getCurrentLockMode( door ) );
  }
  session.getTransaction().commit();
  session.close();
}

相关文章