@SuppressWarnings("unchecked") @Override public List<QueuedTaskHolder> search(TaskSearchQueryParameters searchParameters, Long limit, Long offset) throws ServiceException { try { FullTextQuery fullTextQuery = getSearchTaskQuery(searchParameters); if (offset != null) { fullTextQuery.setFirstResult(offset.intValue()); } if (limit != null) { fullTextQuery.setMaxResults(limit.intValue()); } Sort sort = SortUtils.getLuceneSortWithDefaults(searchParameters.getSort(), QueuedTaskHolderSort.ID); SortFieldUtil.setSort(fullTextQuery, getEntityManager(), QueuedTaskHolder.class, sort); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SECOND_LEVEL_CACHE, DatabaseRetrievalMethod.QUERY); return (List<QueuedTaskHolder>) fullTextQuery.getResultList(); } catch (RuntimeException e) { throw new ServiceException("Error while searching tasks.", e); } }
@SuppressWarnings("unchecked") @Test public void shouldFindAllGamesInIndexBatchQuery() throws Exception { Sleep.sleep( MAX_SLEEP_TIME, () -> { List<Game> games = new ArrayList<>(); FullTextEntityManager fem = this.searchFactory.getFullTextEntityManager( this.em ); games.addAll( fem.createFullTextQuery( new MatchAllDocsQuery(), Game.class ).initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.QUERY ).getResultList() ); System.out.println( "Found " + games.size() + " games (using Hibernate-Search):" ); return assertContainsAllGames( games ); }, 100, "coudln't find all games!" ); }
@SuppressWarnings("unchecked") @Test public void shouldFindAllGamesInIndexFindByIdQuery() throws Exception { Sleep.sleep( MAX_SLEEP_TIME, () -> { List<Game> games = new ArrayList<>(); FullTextEntityManager fem = this.searchFactory.getFullTextEntityManager( this.em ); games.addAll( fem.createFullTextQuery( new MatchAllDocsQuery(), Game.class ).initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ).getResultList() ); System.out.println( "Found " + games.size() + " games (using Hibernate-Search):" ); return assertContainsAllGames( games ); }, 100, "coudln't find all games!" ); }
/** * Return all associated money transfers with given expense report. * * @param expenseReport to look for in money transfers * @return collection of moneyTransfers associated with expenseReport or null. */ @Override public Collection<MoneyTransfer> get(ExpenseReport expenseReport) { if (expenseReport == null) { throw new IllegalArgumentException("expenseReport is null"); } FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(MoneyTransfer.class).get(); Query query = queryBuilder.keyword().onField("report.id").matching(expenseReport.getId()).createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, MoneyTransfer.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); }
@Override public Collection<ExpenseReport> getAllWithNoVerifierAssigned() { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(ExpenseReport.class).get(); Query allAssigned = queryBuilder.range().onField("verifier.id").above(0).createQuery(); // Query query = queryBuilder.bool().must(allAssigned).not().createQuery(); Query statusSubmitted = queryBuilder.keyword().onField("status").matching(ReportStatus.SUBMITTED).createQuery(); Query query = queryBuilder.bool() .must(allAssigned).not() .must(statusSubmitted) .createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, ExpenseReport.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); }
@Override public Collection<ExpenseReport> getAllForSubmitterWithStatus(Person submitter, ReportStatus status) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(ExpenseReport.class).get(); Query forPerson = queryBuilder.keyword().onField("submitter.id").matching(submitter.getId()).createQuery(); Query forStatus = queryBuilder.keyword().onField("status").matching(status).createQuery(); Query query = queryBuilder.bool() .must(forPerson) .must(forStatus) .createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, ExpenseReport.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); }
@Override public Collection<ExpenseReport> getAllForVerifierWithStatus(Person verifier, ReportStatus status) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(ExpenseReport.class).get(); Query forPerson = queryBuilder.keyword().onField("verifier.id").matching(verifier.getId()).createQuery(); Query forStatus = queryBuilder.keyword().onField("status").matching(status).createQuery(); Query query = queryBuilder.bool() .must(forPerson) .must(forStatus) .createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, ExpenseReport.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); }
@Override public FullTextQuery initializeObjectsWith( ObjectLookupMethod lookupMethod, DatabaseRetrievalMethod retrievalMethod) { this.databaseRetrievalMethod = retrievalMethod; return this; }
@Test public void testMultipleEntityQuery() { FullTextEntityManager fem = this.searchFactory.getFullTextEntityManager( this.em ); BooleanQuery query = new BooleanQuery(); query.add( fem.getSearchFactory() .buildQueryBuilder() .forEntity( Place.class ) .get() .keyword() .onField( "name" ) .matching( "Valinor" ).createQuery(), BooleanClause.Occur.SHOULD ); query.add( fem.getSearchFactory().buildQueryBuilder().forEntity( Sorcerer.class ).get().keyword().onField( "name" ).matching( "Saruman" ).createQuery(), BooleanClause.Occur.SHOULD ); FullTextQuery ftQuery = fem.createFullTextQuery( query, Place.class, Sorcerer.class ); assertEquals( 2, ftQuery.getResultSize() ); this.testFoundSorcererAndPlace( ftQuery ); //testCustomUpdatedEntity this for FIND_BY_ID as well ftQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ); this.testFoundSorcererAndPlace( ftQuery ); }
@Test public void canSearchUsingFullTextQuery() { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); //Add full-text superpowers to any EntityManager: FullTextEntityManager ftem = Search.getFullTextEntityManager(entityManager); // Optionally use the QueryBuilder to simplify Query definition: QueryBuilder b = ftem.getSearchFactory().buildQueryBuilder().forEntity( Hike.class ).get(); // A lucene query to look for hike to the Carisbrooke castle: // Note that the query looks for "cariboke" instead of "Carisbrooke" Query lq = b.keyword().onField("description").matching("carisbroke castle").createQuery(); //Transform the Lucene Query in a JPA Query: FullTextQuery ftQuery = ftem.createFullTextQuery(lq, Hike.class); //This is a requirement when using Hibernate OGM instead of ORM: ftQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ); // List matching hikes List<Hike> hikes = ftQuery.getResultList(); assertThat( hikes ).onProperty( "description" ).containsOnly( "Exploring Carisbrooke Castle" ); entityManager.getTransaction().commit(); entityManager.close(); }
@Override public FullTextQuery getFullTextQuery(Query luceneQuery, Class<?>... entities) { FullTextQuery ftq = getFullTextSession().createFullTextQuery(luceneQuery, entities); /* hibernate-ogm 에서는 꼭 DatabaseRetrievalMethod.FIND_BY_ID 를 사용해야 합니다. */ ftq.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return ftq; }
@Override public FullTextQuery getFullTextQuery(Query luceneQuery, Class<?>... entities) { if (isTraceEnabled) log.trace("FullTextQuery를 생성합니다... luceneQuery=[{}], entities=[{}]", luceneQuery, StringTool.listToString(entities)); FullTextQuery ftq = getFullTextSession().createFullTextQuery(luceneQuery, entities); // 필수!!! object lookup 및 DB 조회 방법 설정 // ftq.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return ftq; }
@Test public void hibernateSearchUsage() throws Exception { final Session session = openSession(); final FullTextSession fts = Search.getFullTextSession(session); Transaction transaction = fts.beginTransaction(); int itemCount = 10000; for (int i = 0; i < itemCount; i++) { Insurance insurance = new Insurance(); insurance.setName("Macif"); fts.persist(insurance); } transaction.commit(); fts.clear(); transaction = fts.beginTransaction(); final QueryBuilder b = fts.getSearchFactory() .buildQueryBuilder() .forEntity(Insurance.class) .get(); final Query lq = b.keyword().onField("name").matching("Macif").createQuery(); final FullTextQuery ftq = fts.createFullTextQuery(lq, Insurance.class); ftq.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); final List<Insurance> results = ftq.list(); Assertions.assertThat(results).hasSize(itemCount); for (Insurance o : results) fts.delete(o); transaction.commit(); fts.close(); }
@Override public Collection<Payment> getAllPayments(Person person) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder qb = ftem.getSearchFactory().buildQueryBuilder().forEntity(Payment.class).get(); Query query = qb.keyword().onField("report.submitter.id").matching(person.getId()).createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, Payment.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); // return session.createQuery("SELECT payment FROM Payment payment WHERE payment.report.submitter.id = :personId") // .setParameter("personId", person.getId()).list(); }
@Override public List<Payment> get(ExpenseReport report) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder qb = ftem.getSearchFactory().buildQueryBuilder().forEntity(Payment.class).get(); Query query = qb.keyword().onField("report.id").matching(report.getId()).createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, Payment.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); // return session.createQuery("SELECT payment FROM Payment payment WHERE payment.report.id = :reportId") // .setParameter("reportId", report.getId()).list(); }
public Collection<ExpenseReport> getAllForSubmitter(Person submitter) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(ExpenseReport.class).get(); Query query = queryBuilder.keyword().onField("submitter.id").matching(submitter.getId()).createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, ExpenseReport.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); // return session.createQuery("SELECT report FROM ExpenseReport report WHERE report.submitter.id = :submitterId") // .setParameter("submitterId", submitter.getId()).list(); }
@Override public Collection<ExpenseReport> getAllForVerifier(Person verifier) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(ExpenseReport.class).get(); Query query = queryBuilder.keyword().onField("verifier.id").matching(verifier.getId()).createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, ExpenseReport.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); }
@Override public Collection<ExpenseReport> getAllBy(ReportStatus status) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(ExpenseReport.class).get(); Query query = queryBuilder.keyword().onField("status").matching(status).createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, ExpenseReport.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); }
@Override @SuppressWarnings(value = "unchecked") public Collection<Receipt> getReceipts(Person importedBy) { FullTextEntityManager ftem = Search.getFullTextEntityManager(em); QueryBuilder queryBuilder = ftem.getSearchFactory().buildQueryBuilder().forEntity(Receipt.class).get(); Query query = queryBuilder.keyword().onField("importedBy.id").matching(importedBy.getId()).createQuery(); FullTextQuery fullTextQuery = ftem.createFullTextQuery(query, Receipt.class); fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID); return fullTextQuery.getResultList(); // return session.createQuery("SELECT receipt FROM Receipt receipt WHERE receipt.importedBy.id = :personId") // .setParameter("personId", importedBy.getId()).list(); }
/** * 全文检索 * @param page 分页对象 * @param query 关键字查询对象 * @param queryFilter 查询过滤对象 * @param sort 排序对象 * @return 分页对象 */ @SuppressWarnings("unchecked") public Page<T> search(Page<T> page, BooleanQuery query, BooleanQuery queryFilter, Sort sort){ // 按关键字查询 FullTextQuery fullTextQuery = getFullTextSession().createFullTextQuery(query, entityClass); // 过滤无效的内容 if(queryFilter != null){ fullTextQuery.setFilter(new CachingWrapperFilter(new QueryWrapperFilter(queryFilter))); } // 按时间排序 if(sort != null){ fullTextQuery.setSort(sort); } // 定义分页 page.setCount(fullTextQuery.getResultSize()); fullTextQuery.setFirstResult(page.getFirstResult()); fullTextQuery.setMaxResults(page.getMaxResults()); // 先从持久化上下文中查找对象,如果没有再从二级缓存中查找 fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SECOND_LEVEL_CACHE, DatabaseRetrievalMethod.QUERY); // 返回结果 page.setList(fullTextQuery.list()); return page; }
private HSearchQuery.Fetch getFetch() { return this.databaseRetrievalMethod == DatabaseRetrievalMethod.FIND_BY_ID ? HSearchQuery.Fetch.FIND_BY_ID : HSearchQuery.Fetch.BATCH; }
/** * Refine the strategies used to load entities. * <p> * The lookup method defines whether or not to lookup first in the second level cache or the persistence context * before trying to initialize objects from the database. Defaults to SKIP. * <p> * The database retrieval method defines how objects are loaded from the database. Defaults to QUERY. * <p> * Note that Hibernate Search can deviate from these choices when it makes sense. */ FullTextQuery initializeObjectsWith(ObjectLookupMethod lookupMethod, DatabaseRetrievalMethod retrievalMethod);