org.hibernate.jpa.QueryHints Java Examples
The following examples show how to use
org.hibernate.jpa.QueryHints.
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: CommonDAOSpringImpl.java From EasyEE with MIT License | 6 votes |
/** * CommonDAO 内部方法,NamedQuery * * @param entityManager * entityManager * @param name * name * @param cacheable * cacheable * @param cacheRegion * cacheRegion * @param values * values * @return Query对象 */ private Query createNamedQuery(EntityManager entityManager, String name, boolean cacheable, String cacheRegion, Map<String, Object> values) { Query query = entityManager.createNamedQuery(name.trim()); if (cacheable) { query.setHint(QueryHints.HINT_CACHEABLE, "true"); if (cacheRegion != null && (!cacheRegion.equals(""))) { query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion); } } if (values != null && values.size() > 0) { for (Entry<String, Object> e : values.entrySet()) { query.setParameter(e.getKey(), e.getValue()); } } return query; }
Example #2
Source File: CommonDAOSpringImpl.java From EasyEE with MIT License | 6 votes |
/** * CommonDAO 内部方法,Query * * @param entityManager * entityManager * @param jpql * jqpl * @param cacheable * cacheable * @param cacheRegion * cacheRegion * @param values * values * @return Query对象 */ private Query createQuery(EntityManager entityManager, String jpql, boolean cacheable, String cacheRegion, Map<String, Object> values) { Query query = entityManager.createQuery(jpql); if (cacheable) { query.setHint(QueryHints.HINT_CACHEABLE, "true"); if (cacheRegion != null && (!cacheRegion.equals(""))) { query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion); } } if (values != null && values.size() > 0) { for (Entry<String, Object> e : values.entrySet()) { query.setParameter(e.getKey(), e.getValue()); } } return query; }
Example #3
Source File: CommonDAOSpringImpl.java From EasyEE with MIT License | 6 votes |
/** * CommonDAO 内部方法,NamedQuery * * @param entityManager * entityManager * @param name * name * @param cacheable * cacheable * @param cacheRegion * cacheRegion * @param values * values * @return Query对象 */ private Query createNamedQuery(EntityManager entityManager, String name, boolean cacheable, String cacheRegion, Map<String, Object> values) { Query query = entityManager.createNamedQuery(name.trim()); if (cacheable) { query.setHint(QueryHints.HINT_CACHEABLE, "true"); if (cacheRegion != null && (!cacheRegion.equals(""))) { query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion); } } if (values != null && values.size() > 0) { for (Entry<String, Object> e : values.entrySet()) { query.setParameter(e.getKey(), e.getValue()); } } return query; }
Example #4
Source File: MySQLScrollableResultsStreamingCustomFetchSizeTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
private void stream(EntityManager entityManager) { final AtomicLong sum = new AtomicLong(); try(Stream<Post> postStream = entityManager .createQuery("select p from Post p", Post.class) .setMaxResults(resultSetSize) .setHint(QueryHints.HINT_FETCH_SIZE, resultSetSize) .unwrap(Query.class) .stream()) { postStream.forEach(post -> sum.incrementAndGet()); } assertEquals(resultSetSize, sum.get()); }
Example #5
Source File: CommonDAOSpringImpl.java From EasyEE with MIT License | 6 votes |
/** * CommonDAO 内部方法,Query * * @param entityManager * entityManager * @param jpql * jqpl * @param cacheable * cacheable * @param cacheRegion * cacheRegion * @param values * values * @return Query对象 */ private Query createQuery(EntityManager entityManager, String jpql, boolean cacheable, String cacheRegion, Map<String, Object> values) { Query query = entityManager.createQuery(jpql); if (cacheable) { query.setHint(QueryHints.HINT_CACHEABLE, "true"); if (cacheRegion != null && (!cacheRegion.equals(""))) { query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion); } } if (values != null && values.size() > 0) { for (Entry<String, Object> e : values.entrySet()) { query.setParameter(e.getKey(), e.getValue()); } } return query; }
Example #6
Source File: CommonDAOSpringImpl.java From EasyEE with MIT License | 6 votes |
/** * CommonDAO 内部方法,NamedQuery * * @param entityManager * entityManager * @param name * name * @param cacheable * cacheable * @param cacheRegion * cacheRegion * @param values * values * @return Query对象 */ private Query createNamedQuery(EntityManager entityManager, String name, boolean cacheable, String cacheRegion, Map<String, Object> values) { Query query = entityManager.createNamedQuery(name.trim()); if (cacheable) { query.setHint(QueryHints.HINT_CACHEABLE, "true"); if (cacheRegion != null && (!cacheRegion.equals(""))) { query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion); } } if (values != null && values.size() > 0) { for (Entry<String, Object> e : values.entrySet()) { query.setParameter(e.getKey(), e.getValue()); } } return query; }
Example #7
Source File: CommonDAOSpringImpl.java From EasyEE with MIT License | 6 votes |
/** * CommonDAO 内部方法,Query * * @param entityManager * entityManager * @param jpql * jqpl * @param cacheable * cacheable * @param cacheRegion * cacheRegion * @param values * values * @return Query对象 */ private Query createQuery(EntityManager entityManager, String jpql, boolean cacheable, String cacheRegion, Map<String, Object> values) { Query query = entityManager.createQuery(jpql); if (cacheable) { query.setHint(QueryHints.HINT_CACHEABLE, "true"); if (cacheRegion != null && (!cacheRegion.equals(""))) { query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion); } } if (values != null && values.size() > 0) { for (Entry<String, Object> e : values.entrySet()) { query.setParameter(e.getKey(), e.getValue()); } } return query; }
Example #8
Source File: QueryCacheTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
private List<PostCommentSummary> getPostCommentSummaryByPost(EntityManager entityManager, Long postId) { return entityManager.createQuery( "select new " + " com.vladmihalcea.book.hpjp.hibernate.cache.query.PostCommentSummary(" + " pc.id, " + " p.title, " + " pc.review" + " ) " + "from PostComment pc " + "left join pc.post p " + "where p.id = :postId ", PostCommentSummary.class) .setParameter("postId", postId) .setMaxResults(10) .setHint(QueryHints.HINT_CACHEABLE, true) .getResultList(); }
Example #9
Source File: QueryCacheDTOTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
List<PostSummary> getLatestPostSummaries( EntityManager entityManager, int maxResults, boolean cacheable) { List<PostSummary> latestPosts = entityManager.createQuery( "select new " + " com.vladmihalcea.book.hpjp.hibernate.cache.query.PostSummary(" + " p.id, " + " p.title, " + " p.createdOn, " + " count(pc.id) " + " ) " + "from PostComment pc " + "left join pc.post p " + "group by p.id, p.title " + "order by p.createdOn desc ", PostSummary.class) .setMaxResults(maxResults) .setHint(QueryHints.HINT_CACHEABLE, cacheable) .getResultList(); LOGGER.debug("Latest posts: {}", latestPosts); return latestPosts; }
Example #10
Source File: QueryCacheTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
private List<PostComment> getLatestPostCommentsByPost(EntityManager entityManager) { Post post = entityManager.find(Post.class, 1L); return entityManager.createQuery( "select pc " + "from PostComment pc " + "where pc.post = :post ", PostComment.class) .setParameter("post", post) .setMaxResults(10) .setHint(QueryHints.HINT_CACHEABLE, true) .getResultList(); }
Example #11
Source File: DistinctTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
@Test public void testWithDistinctAndQueryHint() { doInJPA(entityManager -> { List<Post> posts = entityManager.createQuery( "select distinct p " + "from Post p " + "left join fetch p.comments " + "where p.title = :title", Post.class) .setParameter("title", "High-Performance Java Persistence eBook has been released!") .setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false) .getResultList(); LOGGER.info("Fetched the following Post entity identifiers: {}", posts.stream().map(Post::getId).collect(Collectors.toList())); }); }
Example #12
Source File: PlanCacheSizePerformanceTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
protected Query getNativeQuery1(EntityManager entityManager) { return entityManager.createNativeQuery( "select p.id, p.title, c.review * " + "from post_comment c " + "join post p on p.id = c.post_id ") .setFirstResult(10) .setMaxResults(20) .setHint(QueryHints.HINT_FETCH_SIZE, 20); }
Example #13
Source File: PlanCacheSizePerformanceTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
protected Query getEntityQuery1(EntityManager entityManager) { return entityManager.createQuery( "select new " + " com.vladmihalcea.book.hpjp.hibernate.fetching.PostCommentSummary( " + " p.id, p.title, c.review ) " + "from PostComment c " + "join c.post p") .setFirstResult(10) .setMaxResults(20) .setHint(QueryHints.HINT_FETCH_SIZE, 20); }
Example #14
Source File: MySQLScrollableResultsStreamingTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
private void stream(EntityManager entityManager) { final AtomicLong sum = new AtomicLong(); try(Stream<Post> postStream = entityManager .createQuery("select p from Post p", Post.class) .setMaxResults(resultSetSize) .setHint(QueryHints.HINT_FETCH_SIZE, Integer.MIN_VALUE) .unwrap(Query.class) .stream()) { postStream.forEach(post -> sum.incrementAndGet()); } assertEquals(resultSetSize, sum.get()); }
Example #15
Source File: QueryCacheTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
private List<PostComment> getLatestPostCommentsByPostId(EntityManager entityManager) { return entityManager.createQuery( "select pc " + "from PostComment pc " + "where pc.post.id = :postId", PostComment.class) .setParameter("postId", 1L) .setMaxResults(10) .setHint(QueryHints.HINT_CACHEABLE, true) .getResultList(); }
Example #16
Source File: QueryCacheTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
public List<PostComment> getLatestPostComments(EntityManager entityManager) { return entityManager.createQuery( "select pc " + "from PostComment pc " + "order by pc.post.id desc", PostComment.class) .setMaxResults(10) .setHint(QueryHints.HINT_CACHEABLE, true) .getResultList(); }
Example #17
Source File: BidirectionalOneToManyMergeTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
public Post fetchPostWithComments(Long postId) { return doInJPA(entityManager -> { return entityManager.createQuery( "select distinct p " + "from Post p " + "join fetch p.comments " + "where p.id = :postId ", Post.class) .setHint(QueryHints.HINT_READONLY, true) .setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false) .setParameter("postId", postId) .getSingleResult(); }); }
Example #18
Source File: SessionImpl.java From lams with GNU General Public License v2.0 | 5 votes |
protected void applyQuerySettingsAndHints(Query query) { if ( lockOptions.getLockMode() != LockMode.NONE ) { query.setLockMode( getLockMode( lockOptions.getLockMode() ) ); } Object queryTimeout; if ( (queryTimeout = getProperties().get( QueryHints.SPEC_HINT_TIMEOUT ) ) != null ) { query.setHint( QueryHints.SPEC_HINT_TIMEOUT, queryTimeout ); } Object lockTimeout; if( (lockTimeout = getProperties().get( JPA_LOCK_TIMEOUT ))!=null){ query.setHint( JPA_LOCK_TIMEOUT, lockTimeout ); } }
Example #19
Source File: TestProjectionPerformance.java From Hands-On-High-Performance-with-Spring-5 with MIT License | 5 votes |
private void findAccountUsingQueryHint(){ long timeQuery = 0; long iterations = 1000; // Perform 1000 iterations for (int i = 0; i < iterations; i++) { long startQuery = System.currentTimeMillis(); List<Account> lAccounts= entityManager.createQuery("SELECT a FROM Account a").setHint(QueryHints.HINT_READONLY, true).getResultList(); long endQuery = System.currentTimeMillis(); timeQuery += endQuery - startQuery; } _logger.warn("Query Hint: total " + timeQuery + " ms per iteration " + timeQuery / (double)iterations); }
Example #20
Source File: TestQueryCaching.java From Hands-On-High-Performance-with-Spring-5 with MIT License | 5 votes |
@Transactional private void queryCache2(){ _logger.warn("Query Cache"); Query query = entityManager.createQuery("SELECT a FROM Account a WHERE a.accountId=:accountId", Account.class); query.setParameter("accountId", 7L); query.setHint(QueryHints.HINT_CACHEABLE, true); Account account = (Account)query.getSingleResult(); _logger.warn(account); }
Example #21
Source File: TopicMessageRepositoryCustomImpl.java From hedera-mirror-node with Apache License 2.0 | 5 votes |
@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 #22
Source File: QueryPlanCacheBenchmark.java From tutorials with MIT License | 4 votes |
private Query findEmployeesByDesignationQuery(Session session) { return session.createQuery("SELECT e FROM DeptEmployee e " + "WHERE e.title = :designation") .setHint(QueryHints.SPEC_HINT_TIMEOUT, 1000); }
Example #23
Source File: QueryPlanCacheBenchmark.java From tutorials with MIT License | 4 votes |
private Query findEmployeesByDepartmentNameQuery(Session session) { return session.createQuery("SELECT e FROM DeptEmployee e " + "JOIN e.department WHERE e.department.name = :deptName") .setMaxResults(30) .setHint(QueryHints.HINT_FETCH_SIZE, 30); }
Example #24
Source File: PaginationTest.java From high-performance-java-persistence with Apache License 2.0 | 4 votes |
@Test public void testFetchAndPaginateParentWithNoChild() { doInJPA(entityManager -> { entityManager.persist( new Post() .setId(100L) .setTitle("High-Performance Java Persistence - Second Edition") .setCreatedOn( Timestamp.valueOf( LocalDateTime.of( 2018, 10, 8, 12, 0, 0, 0 ) ) ) ); }); List<Post> posts = doInJPA(entityManager -> { DistinctPostResultTransformer resultTransformer = new DistinctPostResultTransformer(entityManager); return entityManager .createNamedQuery("PostWithCommentByRank") .setParameter("titlePattern", "High-Performance Java Persistence %") .setParameter("rank", 2) .setHint(QueryHints.HINT_READONLY, true) .unwrap(NativeQuery.class) .setResultTransformer(resultTransformer) .getResultList(); }); assertEquals(2, posts.size()); Post post1 = posts.get(0); long commentId = ((post1.getId() - 1) * COMMENT_COUNT); post1.addComment( new PostComment() .setId(commentId) .setReview( String.format("Comment nr. %d", commentId) ) .setCreatedOn( Timestamp.valueOf(LocalDateTime.now()) ) ); Post post2 = posts.get(1); post2.removeComment(post2.getComments().get(0)); doInJPA(entityManager -> { entityManager.merge(post1); entityManager.merge(post2); }); }
Example #25
Source File: SessionQueryTimeoutTest.java From high-performance-java-persistence with Apache License 2.0 | 4 votes |
@Override protected void additionalProperties(Properties properties) { properties.setProperty( QueryHints.SPEC_HINT_TIMEOUT, String.valueOf(1000) ); }
Example #26
Source File: SessionImpl.java From lams with GNU General Public License v2.0 | 4 votes |
@Override protected void initQueryFromNamedDefinition(Query query, NamedQueryDefinition namedQueryDefinition) { super.initQueryFromNamedDefinition( query, namedQueryDefinition ); if ( namedQueryDefinition.isCacheable() ) { query.setHint( QueryHints.HINT_CACHEABLE, true ); if ( namedQueryDefinition.getCacheRegion() != null ) { query.setHint( QueryHints.HINT_CACHE_REGION, namedQueryDefinition.getCacheRegion() ); } } if ( namedQueryDefinition.getCacheMode() != null ) { query.setHint( QueryHints.HINT_CACHE_MODE, namedQueryDefinition.getCacheMode() ); } if ( namedQueryDefinition.isReadOnly() ) { query.setHint( QueryHints.HINT_READONLY, true ); } if ( namedQueryDefinition.getTimeout() != null ) { query.setHint( QueryHints.SPEC_HINT_TIMEOUT, namedQueryDefinition.getTimeout() * 1000 ); } if ( namedQueryDefinition.getFetchSize() != null ) { query.setHint( QueryHints.HINT_FETCH_SIZE, namedQueryDefinition.getFetchSize() ); } if ( namedQueryDefinition.getComment() != null ) { query.setHint( QueryHints.HINT_COMMENT, namedQueryDefinition.getComment() ); } if ( namedQueryDefinition.getFirstResult() != null ) { query.setFirstResult( namedQueryDefinition.getFirstResult() ); } if ( namedQueryDefinition.getMaxResults() != null ) { query.setMaxResults( namedQueryDefinition.getMaxResults() ); } if ( namedQueryDefinition.getLockOptions() != null ) { if ( namedQueryDefinition.getLockOptions().getLockMode() != null ) { query.setLockMode( LockModeTypeHelper.getLockModeType( namedQueryDefinition.getLockOptions().getLockMode() ) ); } } if ( namedQueryDefinition.getFlushMode() != null ) { query.setHibernateFlushMode( namedQueryDefinition.getFlushMode() ); } }
Example #27
Source File: AbstractProducedQuery.java From lams with GNU General Public License v2.0 | 4 votes |
@SuppressWarnings( {"UnusedDeclaration"}) public Set<String> getSupportedHints() { return QueryHints.getDefinedHints(); }
Example #28
Source File: ReactiveSessionImpl.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 4 votes |
@Override public <T> CompletionStage<T> reactiveFind( Class<T> entityClass, Object id, LockMode lockMode, Map<String, Object> properties) { checkOpen(); getLoadQueryInfluencers().getEffectiveEntityGraph().applyConfiguredGraph( properties ); Boolean readOnly = properties == null ? null : (Boolean) properties.get( QueryHints.HINT_READONLY ); getLoadQueryInfluencers().setReadOnly( readOnly ); final ReactiveIdentifierLoadAccessImpl<T> loadAccess = new ReactiveIdentifierLoadAccessImpl<>(entityClass) .with( determineAppropriateLocalCacheMode( properties ) ); LockOptions lockOptions; if ( lockMode != null ) { // if ( !LockModeType.NONE.equals( lockModeType) ) { // checkTransactionNeededForUpdateOperation(); // } lockOptions = buildLockOptions( LockModeConverter.convertToLockModeType(lockMode), properties ); loadAccess.with( lockOptions ); } else { lockOptions = null; } return loadAccess.load( (Serializable) id ) .handle( (result, e) -> { if ( e instanceof EntityNotFoundException) { // DefaultLoadEventListener.returnNarrowedProxy may throw ENFE (see HHH-7861 for details), // which find() should not throw. Find() should return null if the entity was not found. // if ( log.isDebugEnabled() ) { // String entityName = entityClass != null ? entityClass.getName(): null; // String identifierValue = id != null ? id.toString() : null ; // log.ignoringEntityNotFound( entityName, identifierValue ); // } return null; } if ( e instanceof ObjectDeletedException) { //the spec is silent about people doing remove() find() on the same PC return null; } if ( e instanceof ObjectNotFoundException) { //should not happen on the entity itself with get throw new IllegalArgumentException( e.getMessage(), e ); } if ( e instanceof MappingException || e instanceof TypeMismatchException || e instanceof ClassCastException ) { throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) ); } if ( e instanceof JDBCException ) { // if ( accessTransaction().getRollbackOnly() ) { // // assume this is the similar to the WildFly / IronJacamar "feature" described under HHH-12472 // return null; // } throw getExceptionConverter().convert( (JDBCException) e, lockOptions ); } if ( e instanceof RuntimeException ) { throw getExceptionConverter().convert( (RuntimeException) e, lockOptions ); } return result; } ) .whenComplete( (v, e) -> getLoadQueryInfluencers().getEffectiveEntityGraph().clear() ); }