Esempio n. 1
0
 private void assertTimeoutOccursOnScroll() {
   FullTextQuery hibernateQuery = fts.createFullTextQuery(noMatchQuery, Clock.class);
   hibernateQuery.setTimeout(10, TimeUnit.MICROSECONDS);
   try {
     hibernateQuery.scroll();
     fail("timeout exception should happen");
   } catch (QueryTimeoutException e) {
     // good
   } catch (Exception e) {
     fail("Expected a QueryTimeoutException");
   }
   fts.clear();
 }
Esempio n. 2
0
  @Override
  public int count(Query query, Criteria crit) {
    assertCriteriaEntity(crit);

    int count = 0;

    FullTextSession fullTextSession = getFullTextSession();
    FullTextQuery fq = fullTextSession.createFullTextQuery(query, Page.class);
    fq.setCriteriaQuery(crit != null ? crit : pageDao.criteria());

    ScrollableResults sr = fq.scroll(ScrollMode.FORWARD_ONLY);
    if (sr.last()) {
      count = sr.getRowNumber();
    }
    sr.close();

    return count;
  }
  /**
   * This is the same test as above with a projection query to show the presence of the ClassBridge
   * impl built fields just in case you don't believe us.
   *
   * @throws Exception
   */
  public void testClassBridgesWithProjection() throws Exception {
    org.hibernate.Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(getDepts1());
    s.persist(getDepts2());
    s.persist(getDepts3());
    s.persist(getDepts4());
    s.flush();
    tx.commit();

    tx = s.beginTransaction();
    FullTextSession session = Search.getFullTextSession(s);

    // The equipment field is the manufacturer field  in the
    // Departments entity after being massaged by passing it
    // through the EquipmentType class. This field is in
    // the Lucene document but not in the Department entity itself.
    QueryParser parser =
        new QueryParser(
            TestConstants.getTargetLuceneVersion(), "equipment", TestConstants.simpleAnalyzer);

    // Check the second ClassBridge annotation
    Query query = parser.parse("equiptype:Cisco");
    org.hibernate.search.FullTextQuery hibQuery =
        session.createFullTextQuery(query, Departments.class);

    hibQuery.setProjection(FullTextQuery.THIS, FullTextQuery.DOCUMENT);

    ScrollableResults projections = hibQuery.scroll();
    assertNotNull(projections);

    projections.beforeFirst();
    projections.next();
    Object[] projection = projections.get();

    assertTrue("DOCUMENT incorrect", projection[0] instanceof Departments);
    assertEquals("id incorrect", 1, ((Departments) projection[0]).getId());
    assertTrue("DOCUMENT incorrect", projection[1] instanceof Document);
    assertEquals("DOCUMENT size incorrect", 8, ((Document) projection[1]).getFields().size());
    assertNotNull("equiptype is null", ((Document) projection[1]).getField("equiptype"));
    assertEquals(
        "equiptype incorrect",
        "Cisco",
        ((Document) projection[1]).getField("equiptype").stringValue());
    assertNotNull("branchnetwork is null", ((Document) projection[1]).getField("branchnetwork"));
    assertEquals(
        "branchnetwork incorrect",
        "Salt Lake City 1A",
        ((Document) projection[1]).getField("branchnetwork").stringValue());

    projections.next();
    projection = projections.get();

    assertTrue("DOCUMENT incorrect", projection[0] instanceof Departments);
    assertEquals("id incorrect", 4, ((Departments) projection[0]).getId());
    assertTrue("DOCUMENT incorrect", projection[1] instanceof Document);
    assertEquals("DOCUMENT size incorrect", 8, ((Document) projection[1]).getFields().size());
    assertNotNull("equiptype is null", ((Document) projection[1]).getField("equiptype"));
    assertEquals(
        "equiptype incorrect",
        "Cisco",
        ((Document) projection[1]).getField("equiptype").stringValue());
    assertNotNull("branchnetwork is null", ((Document) projection[1]).getField("branchnetwork"));
    assertEquals(
        "branchnetwork incorrect",
        "St. George 1D",
        ((Document) projection[1]).getField("branchnetwork").stringValue());

    assertTrue("incorrect result count returned", projections.isLast());
    // cleanup
    for (Object element : s.createQuery("from " + Departments.class.getName()).list()) {
      s.delete(element);
    }
    tx.commit();
    s.close();
  }
 @Override
 public StorageResults visit(Select select) {
   // TMDM-4654: Checks if entity has a composite PK.
   Set<ComplexTypeMetadata> compositeKeyTypes = new HashSet<ComplexTypeMetadata>();
   // TMDM-7496: Search should include references to reused types
   Collection<ComplexTypeMetadata> types =
       new HashSet<ComplexTypeMetadata>(select.accept(new SearchTransitiveClosure()));
   for (ComplexTypeMetadata type : types) {
     if (type.getKeyFields().size() > 1) {
       compositeKeyTypes.add(type);
     }
   }
   if (!compositeKeyTypes.isEmpty()) {
     StringBuilder message = new StringBuilder();
     Iterator it = compositeKeyTypes.iterator();
     while (it.hasNext()) {
       ComplexTypeMetadata compositeKeyType = (ComplexTypeMetadata) it.next();
       message.append(compositeKeyType.getName());
       if (it.hasNext()) {
         message.append(',');
       }
     }
     throw new FullTextQueryCompositeKeyException(message.toString());
   }
   // Removes Joins and joined fields.
   List<Join> joins = select.getJoins();
   if (!joins.isEmpty()) {
     Set<ComplexTypeMetadata> joinedTypes = new HashSet<ComplexTypeMetadata>();
     for (Join join : joins) {
       joinedTypes.add(join.getRightField().getFieldMetadata().getContainingType());
     }
     for (ComplexTypeMetadata joinedType : joinedTypes) {
       types.remove(joinedType);
     }
     List<TypedExpression> filteredFields = new LinkedList<TypedExpression>();
     for (TypedExpression expression : select.getSelectedFields()) {
       if (expression instanceof Field) {
         FieldMetadata fieldMetadata = ((Field) expression).getFieldMetadata();
         if (joinedTypes.contains(fieldMetadata.getContainingType())) {
           TypeMapping mapping =
               mappings.getMappingFromDatabase(fieldMetadata.getContainingType());
           filteredFields.add(
               new Alias(
                   new StringConstant(StringUtils.EMPTY),
                   mapping.getUser(fieldMetadata).getName()));
         } else {
           filteredFields.add(expression);
         }
       } else {
         filteredFields.add(expression);
       }
     }
     selectedFields.clear();
     selectedFields.addAll(filteredFields);
   }
   // Handle condition
   Condition condition = select.getCondition();
   if (condition == null) {
     throw new IllegalArgumentException("Expected a condition in select clause but got 0.");
   }
   // Create Lucene query (concatenates all sub queries together).
   FullTextSession fullTextSession = Search.getFullTextSession(session);
   Query parsedQuery = select.getCondition().accept(new LuceneQueryGenerator(types));
   // Create Hibernate Search query
   Set<Class> classes = new HashSet<Class>();
   for (ComplexTypeMetadata type : types) {
     String className = ClassCreator.getClassName(type.getName());
     try {
       ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
       classes.add(contextClassLoader.loadClass(className));
     } catch (ClassNotFoundException e) {
       throw new RuntimeException("Could not find class '" + className + "'.", e);
     }
   }
   FullTextQuery fullTextQuery =
       fullTextSession.createFullTextQuery(
           parsedQuery, classes.toArray(new Class<?>[classes.size()]));
   // Very important to leave this null (would disable ability to search across different types)
   fullTextQuery.setCriteriaQuery(null);
   fullTextQuery.setSort(Sort.RELEVANCE); // Default sort (if no order by specified).
   query =
       EntityFinder.wrap(
           fullTextQuery,
           (HibernateStorage) storage,
           session); // ensures only MDM entity objects are returned.
   // Order by
   for (OrderBy current : select.getOrderBy()) {
     current.accept(this);
   }
   // Paging
   Paging paging = select.getPaging();
   paging.accept(this);
   pageSize = paging.getLimit();
   boolean hasPaging = pageSize < Integer.MAX_VALUE;
   if (!hasPaging) {
     return createResults(query.scroll(ScrollMode.FORWARD_ONLY));
   } else {
     return createResults(query.list());
   }
 }