Java Code Examples for javax.persistence.TypedQuery#setHint()

The following examples show how to use javax.persistence.TypedQuery#setHint() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestEntityGraph.java    From HibernateTips with MIT License 8 votes vote down vote up
@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.");
}
 
Example 2
Source File: StaticEntityRepositoryImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: HibernateIdentifiableObjectStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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();
}
 
Example 4
Source File: QueryCacheTest.java    From hibernate4-memcached with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: ActionListDAOJpaImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@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);
}
 
Example 6
Source File: TestLogging.java    From HibernateTips with MIT License 6 votes vote down vote up
@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();
}
 
Example 7
Source File: TestEntityGraph.java    From HibernateTips with MIT License 6 votes vote down vote up
@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.");
}
 
Example 8
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 9
Source File: getFidoUser.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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;
    }
}
 
Example 10
Source File: TestLogging.java    From HibernateTips with MIT License 5 votes vote down vote up
@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();
}
 
Example 11
Source File: AbstractModelQuery.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: GenericJpaRepositoryImpl.java    From genericdao with Artistic License 2.0 5 votes vote down vote up
/**
 * 应用二级缓存
 * @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("对当前查询使用查询缓存。");
		}
	}
}
 
Example 13
Source File: TopicMessageRepositoryCustomImpl.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
@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
}
 
Example 14
Source File: HibernateGenericStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 ) );
}
 
Example 15
Source File: InfinispanHibernateCacheLocal.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
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);
   }
}
 
Example 16
Source File: InfinispanHibernateCacheSpringLocal.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
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));
   }
}
 
Example 17
Source File: GenericRepository.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 18
Source File: PersistenceManager.java    From infinispan-simple-tutorials with Apache License 2.0 4 votes vote down vote up
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));
}
 
Example 19
Source File: DataViewerImpl.java    From cia with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}
 
Example 20
Source File: AbstractGenericDAOImpl.java    From cia with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}