javax.persistence.TypedQuery#setHint ( )源码实例Demo

下面列出了javax.persistence.TypedQuery#setHint ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: fido2   文件: getFidoUser.java
@Override
public FidoUsers GetByUsername(Long did, String username) throws SKFEException {
    try {
        TypedQuery<FidoUsers> q = em.createNamedQuery("FidoUsers.findByDidUsername", FidoUsers.class);
        q.setHint("javax.persistence.cache.storeMode", "REFRESH");
        q.setParameter("username", username);
        q.setParameter("did", did);
        FidoUsers fidoUser = q.getSingleResult();
        if (fidoUser != null) {
            verifyDBRecordSignature(did, fidoUser);
        }
        return fidoUser;
    } catch (NoResultException ex) {
        return null;
    }
}
 
源代码2 项目: we-cmdb   文件: StaticEntityRepositoryImpl.java
private <T> TypedQuery<T> doQueryCrossRes(Class<T> domainClazz, CrossResRequest request, boolean selectCount) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    EntityGraph<T> rootEg = entityManager.createEntityGraph(domainClazz);

    CriteriaQuery query = cb.createQuery(domainClazz);
    Root<T> root = query.from(domainClazz);
    if (selectCount) {
        query.select(cb.count(root));
    }
    List<Predicate> predicates = new LinkedList<>();
    queryJoin(cb, query, root, request.getRootFilterPath(), rootEg, null, predicates);

    if (predicates.size() > 0) {
        if (FilterRelationship.Or.equals(request.getFilterRs())) {
            query.where(cb.or(predicates.toArray(new Predicate[0])));
        } else {
            query.where(cb.and(predicates.toArray(new Predicate[0])));
        }
    }
    TypedQuery<T> typedQuery = entityManager.createQuery(query);
    if (!selectCount) {
        typedQuery.setHint("javax.persistence.fetchgraph", rootEg);
    }
    return typedQuery;
}
 
private static void listExistingPersons(EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<Person> cq = cb.createQuery(Person.class);
    Root<Person> from = cq.from(Person.class);
    cq.select(from).orderBy(cb.asc(from.get("name")));
    TypedQuery<Person> q = em.createQuery(cq);
    q.setHint("org.hibernate.cacheable", Boolean.TRUE);
    List<Person> allpersons = q.getResultList();
    if (allpersons.size() != 4) {
        throw new RuntimeException("Incorrect number of results");
    }
    if (!allpersons.get(0).getName().equals("Gizmo")) {
        throw new RuntimeException("Incorrect order of results");
    }
    StringBuilder sb = new StringBuilder("list of stored Person names:\n\t");
    for (Person p : allpersons) {
        p.describeFully(sb);
    }
    sb.append("\nList complete.\n");
    System.out.print(sb);
}
 
源代码4 项目: HibernateTips   文件: TestEntityGraph.java
@SuppressWarnings("unchecked")
@Test
public void selectWithEntityGraph() {
	log.info("... selectWithEntityGraph ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	EntityGraph<Author> graph = em.createEntityGraph(Author.class);
	graph.addAttributeNodes(Author_.books);
	
	TypedQuery<Author> q = em.createQuery("SELECT a FROM Author a WHERE a.id = 1", Author.class);
	q.setHint("javax.persistence.fetchgraph", graph);
	Author a = q.getSingleResult();
	
	em.getTransaction().commit();
	em.close();
	
	log.info(a.getFirstName()+" "+a.getLastName()+" wrote "+a.getBooks().size()+" books.");
}
 
源代码5 项目: HibernateTips   文件: TestEntityGraph.java
@Test
public void selectWithNamedEntityGraph() {
	log.info("... selectWithNamedEntityGraph ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	EntityGraph<?> graph = em.createEntityGraph("graph.AuthorBooks");
	TypedQuery<Author> q = em.createQuery("SELECT a FROM Author a WHERE a.id = 1", Author.class);
	q.setHint("javax.persistence.fetchgraph", graph);
	Author a = q.getSingleResult();
	
	em.getTransaction().commit();
	em.close();
	
	log.info(a.getFirstName()+" "+a.getLastName()+" wrote "+a.getBooks().size()+" books.");
}
 
源代码6 项目: HibernateTips   文件: TestLogging.java
@Test
public void selectAuthorsCriteria() {
	log.info("... selectAuthorsCriteria ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Author> cq = cb.createQuery(Author.class);
	Root<Author> root = cq.from(Author.class);
	cq.select(root);
	ParameterExpression<Long> idParam = cb.parameter(Long.class, "id");
	cq.where(cb.equal(root.get("id"), idParam));
	TypedQuery<Author> q = em.createQuery(cq);
	q.setParameter("id", 1L);
	q.setHint("org.hibernate.comment", "This is my comment");
	q.getSingleResult();

	em.getTransaction().commit();
	em.close();
}
 
源代码7 项目: rice   文件: ActionListDAOJpaImpl.java
/**
 * {@inheritDoc}
 */
@Override
public DocumentRouteHeaderValue getMinimalRouteHeader(String documentId) {
    // This graph is defined on the DocumentRouteHeaderValue class.
    EntityGraph<DocumentRouteHeaderValue> entityGraph =
            (EntityGraph<DocumentRouteHeaderValue>) entityManager.createEntityGraph("DocumentRouteHeaderValue.ActionListAttributesOnly");
    TypedQuery<DocumentRouteHeaderValue> query = entityManager.createQuery("SELECT rh FROM DocumentRouteHeaderValue rh WHERE rh.documentId = :documentId", DocumentRouteHeaderValue.class );
    // By using the graph - all properties but those on the graph should have
    // a lazy proxy in place.  Attempting to access any of those *should* cause the
    // rest of the properties to load.
    query.setHint("javax.persistence.fetchgraph", entityGraph);
    query.setParameter("documentId", documentId);
    List<DocumentRouteHeaderValue> result = query.getResultList();
    if ( result.isEmpty() ) {
        return null;
    }
    return result.get(0);
}
 
源代码8 项目: hibernate4-memcached   文件: QueryCacheTest.java
private List<Author> getAuthorsWithQuery(String logMessage, String country) {
	EntityManager em = EntityTestUtils.start();

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Author> cq = cb.createQuery(Author.class);
	Root<Author> author = cq.from(Author.class);
	cq.select(author);
	cq.where(cb.equal(author.get("country"), country));

	TypedQuery<Author> query = em.createQuery(cq);
	query.setHint("org.hibernate.cacheable", true);
	query.setHint("org.hibernate.cacheRegion", "author-by-country");

	log.warn("before call {} --", logMessage);
	List<Author> beforeResults = query.getResultList();
	log.warn("{} : {}", logMessage, beforeResults);
	EntityTestUtils.stop(em);
	return beforeResults;
}
 
@Override
public List<String> getUidsCreatedBefore( Date date )
{
    CriteriaBuilder builder = getCriteriaBuilder();

    CriteriaQuery<String> query = builder.createQuery( String.class );

    Root<T> root = query.from( getClazz() );

    query.select( root.get( "uid" ) );
    query.where( builder.lessThan( root.get( "created" ), date ) );

    TypedQuery<String> typedQuery = getSession().createQuery( query );
    typedQuery.setHint( JpaQueryUtils.HIBERNATE_CACHEABLE_HINT, true );

    return typedQuery.getResultList();
}
 
@Override
public Stream<TopicMessage> findByFilter(TopicMessageFilter filter) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<TopicMessage> query = cb.createQuery(TopicMessage.class);
    Root<TopicMessage> root = query.from(TopicMessage.class);

    Predicate predicate = cb.and(
            cb.equal(root.get("realmNum"), filter.getRealmNum()),
            cb.equal(root.get("topicNum"), filter.getTopicNum()),
            cb.greaterThanOrEqualTo(root.get("consensusTimestamp"), converter.convert(filter.getStartTime()))
    );

    if (filter.getEndTime() != null) {
        predicate = cb.and(predicate, cb
                .lessThan(root.get("consensusTimestamp"), converter.convert(filter.getEndTime())));
    }

    query = query.select(root).where(predicate).orderBy(cb.asc(root.get("consensusTimestamp")));

    TypedQuery<TopicMessage> typedQuery = entityManager.createQuery(query);
    typedQuery.setHint(QueryHints.HINT_READONLY, true);

    if (filter.hasLimit()) {
        typedQuery.setMaxResults((int) filter.getLimit());
    }

    return typedQuery.getResultList().stream(); // getResultStream()'s cursor doesn't work with reactive streams
}
 
源代码11 项目: elexis-3-core   文件: AbstractModelQuery.java
private TypedQuery<?> getTypedQuery(){
	// apply the predicate groups to the criteriaQuery
	int groups = predicateGroups.getPredicateGroupsSize();
	if (groups > 0) {
		if (groups == 2
			&& (EntityWithDeleted.class.isAssignableFrom(entityClazz) && !includeDeleted)) {
			andJoinGroups();
			groups = predicateGroups.getPredicateGroupsSize();
		}
		
		if (groups == 1) {
			criteriaQuery =
				criteriaQuery.where(predicateGroups.getCurrentPredicateGroup().getPredicate());
		} else {
			throw new IllegalStateException("Query has open groups [" + groups + "]");
		}
		
		criteriaQuery.orderBy(orderByList);
	}
	TypedQuery<?> query = entityManager.createQuery(criteriaQuery);
	// update cache with results (https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Query_Hints)
	if (refreshCache) {
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
	}
	if (limit > 0) {
		query.setMaxResults(limit);
	}
	return query;
}
 
源代码12 项目: HibernateTips   文件: TestLogging.java
@Test
public void selectAuthorsJPQL() {
	log.info("... selectAuthorsJPQL ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	TypedQuery<Author> q = em.createQuery("SELECT a FROM Author a WHERE a.id = :id", Author.class);
	q.setParameter("id", 1L);
	q.setHint("org.hibernate.comment", "This is my comment");
	q.getSingleResult();

	em.getTransaction().commit();
	em.close();
}
 
源代码13 项目: genericdao   文件: GenericJpaRepositoryImpl.java
/**
 * 应用二级缓存
 * @param typedQuery
 * @param spec
 */
protected void applySecondLevelCache(TypedQuery<?> typedQuery , Specification<T> spec) {
	if(spec != null && spec instanceof CacheableSpecification){
		CacheableSpecification cacheableSpecification = (CacheableSpecification)spec ;
		//设置jpa查询缓存参数
		if(cacheableSpecification.isCacheable()){
			typedQuery.setHint("org.hibernate.cacheable", true); 
			log.info("对当前查询使用查询缓存。");
		}
	}
}
 
源代码14 项目: dhis2-core   文件: HibernateGenericStore.java
/**
 * Get executable TypedQuery from JpaQueryParameter.
 *
 * @return executable TypedQuery
 */
protected final TypedQuery<T> getTypedQuery( CriteriaBuilder builder, JpaQueryParameters<T> parameters )
{
    List<Function<Root<T>, Predicate>> predicateProviders = parameters.getPredicates();
    List<Function<Root<T>, Order>> orderProviders = parameters.getOrders();
    preProcessPredicates( builder, predicateProviders );

    CriteriaQuery<T> query = builder.createQuery( getClazz() );
    Root<T> root = query.from( getClazz() );
    query.select( root );

    if ( !predicateProviders.isEmpty() )
    {
        List<Predicate> predicates = predicateProviders.stream().map( t -> t.apply( root ) ).collect( Collectors.toList() );
        query.where( predicates.toArray( new Predicate[0] ) );
    }

    if ( !orderProviders.isEmpty() )
    {
        List<Order> orders = orderProviders.stream().map( o -> o.apply( root ) ).collect( Collectors.toList() );
        query.orderBy( orders );
    }

    TypedQuery<T> typedQuery = getExecutableTypedQuery( query );

    if ( parameters.hasFirstResult() )
    {
        typedQuery.setFirstResult( parameters.getFirstResult() );
    }

    if ( parameters.hasMaxResult() )
    {
        typedQuery.setMaxResults( parameters.getMaxResults() );
    }

    return typedQuery
        .setHint( QueryHints.CACHEABLE, parameters.isCacheable( cacheable ) );
}
 
private static void queryEntities() {
   try (Session em = createEntityManagerWithStatsCleared()) {
      TypedQuery<Event> query = em.createQuery("from Event", Event.class);
      query.setHint("org.hibernate.cacheable", Boolean.TRUE);
      List<Event> events = query.getResultList();
      System.out.printf("Queried events: %s%n", events);
   }
}
 
private void queryEntities() {
   try (Session em = createEntityManagerWithStatsCleared()) {
      TypedQuery<Event> query = em.createQuery("from Event", Event.class);
      query.setHint("org.hibernate.cacheable", Boolean.TRUE);
      List<Event> events = query.getResultList();
      log.info(String.format("Queried events: %s%n", events));
   }
}
 
源代码17 项目: javaee-lab   文件: GenericRepository.java
protected void applyCacheHints(TypedQuery<?> typedQuery, SearchParameters sp) {
    if (sp.isCacheable()) {
        typedQuery.setHint("org.hibernate.cacheable", true);

        if (sp.hasCacheRegion()) {
            typedQuery.setHint("org.hibernate.cacheRegion", sp.getCacheRegion());
        } else {
            typedQuery.setHint("org.hibernate.cacheRegion", cacheRegion);
        }
    }
}
 
public void queryEntities(StringBuilder out) {
   TypedQuery<Event> query = em.createQuery("from Event", Event.class);
   query.setHint("org.hibernate.cacheable", Boolean.TRUE);
   List<Event> events = query.getResultList();
   out.append(String.format("Queried events: %s%n", events));
}
 
源代码19 项目: cia   文件: DataViewerImpl.java
/**
 * Adds the cache hints.
 *
 * @param typedQuery
 *            the typed query
 * @param comment
 *            the comment
 */
private static void addCacheHints(final TypedQuery<?> typedQuery, final String comment) {
	typedQuery.setHint("org.hibernate.cacheMode", CacheMode.NORMAL);
	typedQuery.setHint("org.hibernate.cacheable", Boolean.TRUE);
	typedQuery.setHint("org.hibernate.comment", comment);
}
 
源代码20 项目: cia   文件: AbstractGenericDAOImpl.java
/**
 * Adds the cache hints.
 *
 * @param typedQuery
 *            the typed query
 * @param comment
 *            the comment
 */
protected final void addCacheHints(final TypedQuery<?> typedQuery, final String comment) {
	typedQuery.setHint("org.hibernate.cacheMode", CacheMode.NORMAL);
	typedQuery.setHint("org.hibernate.cacheable", Boolean.TRUE);
	typedQuery.setHint("org.hibernate.comment", comment);
}