Esempio n. 1
0
  @Test
  @SkipForDialect(
      value = {SybaseASE15Dialect.class, Sybase11Dialect.class},
      comment = "Sybase does not support @Lob")
  public void testCreateIndexSearchEntityWithLobField() {
    // create and index
    Session session = openSession();
    Transaction tx = session.beginTransaction();

    LobHolder lobHolder = new LobHolder();
    lobHolder.setVeryLongText("this text is very long ...");
    session.persist(lobHolder);

    tx.commit();
    session.close();

    // search
    session = openSession();
    tx = session.beginTransaction();
    FullTextSession fullTextSession = Search.getFullTextSession(session);

    QueryBuilder qb =
        fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(LobHolder.class).get();
    Query query = qb.keyword().onField("veryLongText").matching("text").createQuery();

    FullTextQuery hibernateQuery = fullTextSession.createFullTextQuery(query);
    List<LobHolder> result = hibernateQuery.list();
    assertEquals("We should have a match for the single LobHolder", 1, result.size());

    tx.commit();
    session.close();
  }
  @Test
  public void testUpdateOnImplicitJoinFails() {
    Session s = openSession();
    Transaction t = s.beginTransaction();

    Human human = new Human();
    human.setName(new Name("Steve", 'E', null));

    Human mother = new Human();
    mother.setName(new Name("Jane", 'E', null));
    human.setMother(mother);

    s.save(human);
    s.save(mother);
    s.flush();

    t.commit();

    t = s.beginTransaction();
    try {
      s.createQuery("update Human set mother.name.initial = :initial")
          .setString("initial", "F")
          .executeUpdate();
      fail("update allowed across implicit join");
    } catch (QueryException e) {
    }

    s.createQuery("delete Human where mother is not null").executeUpdate();
    s.createQuery("delete Human").executeUpdate();
    t.commit();
    s.close();
  }
  /**
   * Tests that the document id must be unique
   *
   * @throws Exception in case the test fails.
   */
  @Test
  public void testDocumentIdMustBeUnique() throws Exception {
    Article hello = new Article();
    hello.setDocumentId(1);
    hello.setText("Hello World");

    Article goodbye = new Article();
    goodbye.setDocumentId(1);
    goodbye.setText("Goodbye World");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.save(hello);
    s.save(goodbye);
    tx.commit();
    s.clear();

    tx = s.beginTransaction();
    try {
      Search.getFullTextSession(s)
          .createFullTextQuery(new TermQuery(new Term("text", "world")))
          .list();
      fail("Test should fail, because document id is not unique.");
    } catch (SearchException e) {
      assertEquals(
          "Loading entity of type org.hibernate.search.test.id.Article using 'documentId' as document id and '1' as value was not unique",
          e.getMessage());
    }
    tx.commit();
    s.close();
  }
  @Test
  public void testInsertIntoSuperclassPropertiesFails() {
    TestData data = new TestData();
    data.prepare();

    Session s = openSession();
    Transaction t = s.beginTransaction();

    try {
      s.createQuery("insert into Human (id, bodyWeight) select id, bodyWeight from Lizard")
          .executeUpdate();
      fail("superclass prop insertion did not error");
    } catch (QueryException e) {
      // expected result
    }

    t.commit();
    t = s.beginTransaction();

    s.createQuery("delete Animal where mother is not null").executeUpdate();
    s.createQuery("delete Animal where father is not null").executeUpdate();
    s.createQuery("delete Animal").executeUpdate();

    t.commit();
    s.close();

    data.cleanup();
  }
  @Test
  public void testIncrementCounterVersion() {
    Session s = openSession();
    Transaction t = s.beginTransaction();

    IntegerVersioned entity = new IntegerVersioned("int-vers");
    s.save(entity);
    t.commit();
    s.close();

    int initialVersion = entity.getVersion();

    s = openSession();
    t = s.beginTransaction();
    int count = s.createQuery("update versioned IntegerVersioned set name = name").executeUpdate();
    assertEquals("incorrect exec count", 1, count);
    t.commit();

    t = s.beginTransaction();
    entity = (IntegerVersioned) s.load(IntegerVersioned.class, entity.getId());
    assertEquals("version not incremented", initialVersion + 1, entity.getVersion());

    s.delete(entity);
    t.commit();
    s.close();
  }
Esempio n. 6
0
 @Test
 public void testSaveLoad() {
   Long id = null;
   Session session = SessionUtil.getSession();
   Transaction tx = session.beginTransaction();
   SimpleObject obj = new SimpleObject();
   obj.setKey("sl");
   obj.setValue(10L);
   session.save(obj);
   assertNotNull(obj.getId());
   id = obj.getId();
   tx.commit();
   session.close();
   session = SessionUtil.getSession();
   tx = session.beginTransaction();
   SimpleObject o2 = (SimpleObject) session.load(SimpleObject.class, id);
   assertEquals(o2.getKey(), "sl");
   assertNotNull(o2.getValue());
   assertEquals(o2.getValue().longValue(), 10L);
   SimpleObject o3 = (SimpleObject) session.load(SimpleObject.class, id);
   // Since o2 and o3 were loaded in the same session, they are not only
   // equivalent - as shown by equals() - but equal, as shown by ==
   // since obj was loaded from a different session, it is equivalent but not ==
   assertEquals(o2, o3);
   assertEquals(obj, o2);
   assertTrue(o2 == o3);
   assertFalse(obj == o2);
   tx.commit();
   session.close();
 }
Esempio n. 7
0
  public void testSummarize() throws Exception {
    // Create Transaction to be summarized
    Transaction tx = gls.beginTransaction();
    gls.post(tj, createTransaction("Txn 1"));
    gls.post(tj, createTransaction("Txn 2"));
    tx.commit();

    // Fetch the balances
    A_0 = gls.getBalance(tj, A);
    A_858 = gls.getBalance(tj, A, (short) 858);
    B_0 = gls.getBalance(tj, B);
    B_858 = gls.getBalance(tj, B, (short) 858);
    System.out.println("--- pre-balances --- ");
    System.out.println("  A(0): " + A_0);
    System.out.println("A(858): " + A_858);
    System.out.println("  B(0): " + B_0);
    System.out.println("B(858): " + B_858);

    // Summarize
    tx = gls.beginTransaction();
    gls.summarize(tj, POSTDATE, POSTDATE, "Summarized Txn", new short[] {0, 858});
    tx.commit();

    // Test post summarize balances
    System.out.println("--- post-balances ---");
    System.out.println("  A(0): " + gls.getBalance(tj, A));
    System.out.println("A(858): " + gls.getBalance(tj, A, (short) 858));
    System.out.println("  B(0): " + gls.getBalance(tj, B));
    System.out.println("B(858): " + gls.getBalance(tj, B, (short) 858));

    assertEquals(A_0, gls.getBalance(tj, A));
    assertEquals(A_858, gls.getBalance(tj, A, (short) 858));
    assertEquals(B_0, gls.getBalance(tj, B));
    assertEquals(B_858, gls.getBalance(tj, B, (short) 858));
  }
 public void testBlob() throws Exception {
   Session s;
   Transaction tx;
   s = openSession();
   tx = s.beginTransaction();
   CompiledCode cc = new CompiledCode();
   Byte[] header = new Byte[2];
   header[0] = new Byte((byte) 3);
   header[1] = new Byte((byte) 0);
   cc.setHeader(header);
   int codeSize = 5;
   byte[] full = new byte[codeSize];
   for (int i = 0; i < codeSize; i++) {
     full[i] = (byte) (1 + i);
   }
   cc.setFullCode(full);
   s.persist(cc);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   CompiledCode recompiled = (CompiledCode) s.get(CompiledCode.class, cc.getId());
   assertEquals(recompiled.getHeader()[1], cc.getHeader()[1]);
   assertEquals(recompiled.getFullCode()[codeSize - 1], cc.getFullCode()[codeSize - 1]);
   tx.commit();
   s.close();
 }
 public void testSerializableToBlob() throws Exception {
   Book book = new Book();
   Editor editor = new Editor();
   editor.setName("O'Reilly");
   book.setEditor(editor);
   book.setCode2(new char[] {'r'});
   Session s;
   Transaction tx;
   s = openSession();
   tx = s.beginTransaction();
   s.persist(book);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   Book loadedBook = (Book) s.get(Book.class, book.getId());
   assertNotNull(loadedBook.getEditor());
   assertEquals(book.getEditor().getName(), loadedBook.getEditor().getName());
   loadedBook.setEditor(null);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   loadedBook = (Book) s.get(Book.class, book.getId());
   assertNull(loadedBook.getEditor());
   tx.commit();
   s.close();
 }
  public void testBroken() throws Exception {
    if (getDialect() instanceof Oracle9Dialect) return;
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Broken b = new Fixed();
    b.setId(new Long(123));
    b.setOtherId("foobar");
    s.save(b);
    s.flush();
    b.setTimestamp(new Date());
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.update(b);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    b = (Broken) s.load(Broken.class, b);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.delete(b);
    t.commit();
    s.close();
  }
  public void testSqlFunctionAsAlias() throws Exception {
    String functionName = locateAppropriateDialectFunctionNameForAliasTest();
    if (functionName == null) {
      log.info("Dialect does not list any no-arg functions");
      return;
    }

    log.info("Using function named [" + functionName + "] for 'function as alias' test");
    String query =
        "select "
            + functionName
            + " from Simple as "
            + functionName
            + " where "
            + functionName
            + ".id = 10";

    Session s = openSession();
    Transaction t = s.beginTransaction();
    Simple simple = new Simple();
    simple.setName("Simple 1");
    s.save(simple, new Long(10));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    List result = s.find(query);
    assertTrue(result.size() == 1);
    assertTrue(result.get(0) instanceof Simple);
    s.delete(result.get(0));
    t.commit();
    s.close();
  }
  @Test
  public void testSpecificQueryRegionEviction() {
    int entityCount = 10;
    insertDummyEntities(entityCount, 0);
    // miss 1 query list entities
    Session session = sf.openSession();
    Transaction txn = session.beginTransaction();
    Query query = session.createQuery("from " + DummyEntity.class.getName());
    query.setCacheable(true).setCacheRegion("newregionname");
    query.list();
    txn.commit();
    session.close();
    // query is cached

    // query is invalidated
    sf.getCache().evictQueryRegion("newregionname");

    // miss 1 query
    session = sf.openSession();
    txn = session.beginTransaction();
    query = session.createQuery("from " + DummyEntity.class.getName());
    query.setCacheable(true);
    query.list();
    txn.commit();
    session.close();

    assertEquals(0, sf.getStatistics().getQueryCacheHitCount());
    assertEquals(2, sf.getStatistics().getQueryCacheMissCount());
  }
  public void testGetLoad() {
    clearCounts();

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    Employer emp = new Employer();
    s.persist(emp);
    Node node = new Node("foo");
    Node parent = new Node("bar");
    parent.addChild(node);
    s.persist(parent);
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.get(Employer.class, emp.getId());
    assertTrue(Hibernate.isInitialized(emp));
    assertFalse(Hibernate.isInitialized(emp.getEmployees()));
    node = (Node) s.get(Node.class, node.getName());
    assertTrue(Hibernate.isInitialized(node));
    assertFalse(Hibernate.isInitialized(node.getChildren()));
    assertFalse(Hibernate.isInitialized(node.getParent()));
    assertNull(s.get(Node.class, "xyz"));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.load(Employer.class, emp.getId());
    emp.getId();
    assertFalse(Hibernate.isInitialized(emp));
    node = (Node) s.load(Node.class, node.getName());
    assertEquals(node.getName(), "foo");
    assertFalse(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.get("org.hibernate.ejb.test.ops.Employer", emp.getId());
    assertTrue(Hibernate.isInitialized(emp));
    node = (Node) s.get("org.hibernate.ejb.test.ops.Node", node.getName());
    assertTrue(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.load("org.hibernate.ejb.test.ops.Employer", emp.getId());
    emp.getId();
    assertFalse(Hibernate.isInitialized(emp));
    node = (Node) s.load("org.hibernate.ejb.test.ops.Node", node.getName());
    assertEquals(node.getName(), "foo");
    assertFalse(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    assertFetchCount(0);
  }
  @Test
  public void testProjectedValueGetsConvertedToNull() throws Exception {
    ProgrammaticConfiguredValue nullValue = new ProgrammaticConfiguredValue(null);

    FullTextSession fullTextSession = Search.getFullTextSession(openSession());
    Transaction tx = fullTextSession.beginTransaction();
    getSession().save(nullValue);
    tx.commit();

    fullTextSession.clear();
    tx = fullTextSession.beginTransaction();

    Query query = new MatchAllDocsQuery();
    FullTextQuery fullTextQuery =
        fullTextSession.createFullTextQuery(query, ProgrammaticConfiguredValue.class);
    fullTextQuery.setProjection("id", "value");
    fullTextQuery.setResultTransformer(new ProjectionToMapResultTransformer());
    List<?> mappedResults = fullTextQuery.list();
    assertTrue("Wrong result size", mappedResults.size() == 1);

    Map<?, ?> map = (Map<?, ?>) mappedResults.get(0);
    Integer id = (Integer) map.get("id");
    assertNotNull(id);

    String value = (String) map.get("value");
    assertEquals("The null token should be converted back to null", null, value);

    tx.commit();
    fullTextSession.close();
  }
Esempio n. 15
0
  @Test
  public void testOrderedListAndCompositeId() throws Exception {
    Session session = openSession();
    Transaction transaction = session.beginTransaction();
    Race race = new Race();
    race.setRaceId(new Race.RaceId(23, 75));
    Runner runner = new Runner();
    runner.setAge(37);
    runner.setRunnerId(new Runner.RunnerId("Emmanuel", "Bernard"));
    Runner runner2 = new Runner();
    runner2.setAge(105);
    runner2.setRunnerId(new Runner.RunnerId("Pere", "Noel"));
    race.getRunnersByArrival().add(runner);
    race.getRunnersByArrival().add(runner2);
    session.persist(race);
    session.persist(runner);
    session.persist(runner2);
    transaction.commit();

    session.clear();

    transaction = session.beginTransaction();
    race = (Race) session.get(Race.class, race.getRaceId());
    assertThat(race.getRunnersByArrival()).hasSize(2);
    assertThat(race.getRunnersByArrival().get(0).getRunnerId().getFirstname())
        .isEqualTo("Emmanuel");
    session.delete(race.getRunnersByArrival().get(0));
    session.delete(race.getRunnersByArrival().get(1));
    session.delete(race);
    transaction.commit();

    session.close();
    checkCleanCache();
  }
  public void testUnconstrained() {
    Session session = openSession();
    Transaction tx = session.beginTransaction();
    Person p = new Person("gavin");
    p.setEmployeeId("123456");
    session.persist(p);
    tx.commit();
    session.close();

    session = openSession();
    tx = session.beginTransaction();
    p = (Person) session.get(Person.class, "gavin");
    assertNull(p.getEmployee());
    p.setEmployee(new Employee("123456"));
    tx.commit();
    session.close();

    session = openSession();
    tx = session.beginTransaction();
    p = (Person) session.get(Person.class, "gavin");
    assertTrue(Hibernate.isInitialized(p.getEmployee()));
    assertNotNull(p.getEmployee());
    session.delete(p);
    tx.commit();
    session.close();
  }
Esempio n. 17
0
  public void testSQLQueryInterface() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Organization ifa = new Organization("IFA");
    Organization jboss = new Organization("JBoss");
    Person gavin = new Person("Gavin");
    Employment emp = new Employment(gavin, jboss, "AU");

    s.persist(ifa);
    s.persist(jboss);
    s.persist(gavin);
    s.persist(emp);

    List l =
        s.createSQLQuery(getOrgEmpRegionSQL())
            .addEntity("org", Organization.class)
            .addJoin("emp", "org.employments")
            .addScalar("regionCode", Hibernate.STRING)
            .list();
    assertEquals(2, l.size());

    l =
        s.createSQLQuery(getOrgEmpPersonSQL())
            .addEntity("org", Organization.class)
            .addJoin("emp", "org.employments")
            .addJoin("pers", "emp.employee")
            .list();
    assertEquals(l.size(), 1);

    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();

    l =
        s.createSQLQuery(
                "select {org.*}, {emp.*} "
                    + "from ORGANIZATION org "
                    + "     left outer join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER, ORGANIZATION org2")
            .addEntity("org", Organization.class)
            .addJoin("emp", "org.employments")
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE)
            .list();
    assertEquals(l.size(), 2);

    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();

    s.delete(emp);
    s.delete(gavin);
    s.delete(ifa);
    s.delete(jboss);

    t.commit();
    s.close();
  }
  @Test
  public void testDeclaredValues() {
    Session s;
    Transaction tx;
    s = openSession();
    tx = s.beginTransaction();
    Country c = new Country();
    c.setName("France");
    AmericaCupClass f = new AmericaCupClass();
    f.setSize(2);
    f.setCountry(c);
    s.persist(c);
    s.persist(f);
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    f = (AmericaCupClass) s.get(AmericaCupClass.class, f.getId());
    assertNotNull(f);
    assertEquals(c, f.getCountry());
    assertEquals(2, f.getSize());
    s.delete(f);
    s.delete(f.getCountry());
    tx.commit();
    s.close();
  }
  /** The ejb3 find() method maps to the Hibernate get() method */
  public void testGetSemantics() {
    Long nonExistentId = new Long(-1);
    Session s = openSession();
    Transaction txn = s.beginTransaction();
    Item item = (Item) s.get(Item.class, nonExistentId);
    assertNull("get() of non-existent entity did not return null", item);
    txn.commit();
    s.close();

    s = openSession();
    txn = s.beginTransaction();
    // first load() it to generate a proxy...
    item = (Item) s.load(Item.class, nonExistentId);
    assertFalse(Hibernate.isInitialized(item));
    // then try to get() it to make sure we get an exception
    try {
      s.get(Item.class, nonExistentId);
      fail("force load did not fail on non-existent entity");
    } catch (EntityNotFoundException e) {
      // expected behavior
    } catch (AssertionFailedError e) {
      throw e;
    } catch (Throwable t) {
      fail("unexpected exception type on non-existent entity force load : " + t);
    }
    txn.commit();
    s.close();
  }
  @Test
  public void testCompositePk() throws Exception {
    Session s;
    Transaction tx;
    s = openSession();
    tx = s.beginTransaction();
    Carrot c = new Carrot();
    VegetablePk pk = new VegetablePk();
    pk.setFarmer("Bill");
    pk.setHarvestDate("2004-08-15");
    c.setId(pk);
    c.setLength(23);
    s.persist(c);
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    Vegetable v = (Vegetable) s.createCriteria(Vegetable.class).uniqueResult();
    assertTrue(v instanceof Carrot);
    Carrot result = (Carrot) v;
    assertEquals(23, result.getLength());
    tx.commit();
    s.close();
  }
  @Test
  public void testInsertWithMismatchedTypes() {
    TestData data = new TestData();
    data.prepare();

    Session s = openSession();
    Transaction t = s.beginTransaction();
    try {
      s.createQuery("insert into Pickup (owner, vin, id) select id, vin, owner from Car")
          .executeUpdate();
      fail("mismatched types did not error");
    } catch (QueryException e) {
      // expected result
    }

    t.commit();
    t = s.beginTransaction();

    s.createQuery("delete Vehicle").executeUpdate();

    t.commit();
    s.close();

    data.cleanup();
  }
  @Test
  public void testAnalyzerDef() throws Exception {
    Address address = new Address();
    address.setStreet1("3340 Peachtree Rd NE");
    address.setStreet2("JBoss");

    FullTextSession s = Search.getFullTextSession(openSession());
    Transaction tx = s.beginTransaction();
    s.persist(address);
    tx.commit();

    s.clear();

    tx = s.beginTransaction();

    QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer);
    org.apache.lucene.search.Query luceneQuery = parser.parse("street1_ngram:pea");

    final FullTextQuery query = s.createFullTextQuery(luceneQuery);
    assertEquals("Analyzer inoperant", 1, query.getResultSize());

    s.delete(query.list().get(0));
    tx.commit();
    s.close();
  }
  @Test
  public void testInsertAcrossMappedJoinFails() {
    TestData data = new TestData();
    data.prepare();

    Session s = openSession();
    Transaction t = s.beginTransaction();

    try {
      s.createQuery("insert into Joiner (name, joinedName) select vin, owner from Car")
          .executeUpdate();
      fail("mapped-join insertion did not error");
    } catch (QueryException e) {
      // expected result
    }

    t.commit();
    t = s.beginTransaction();

    s.createQuery("delete Joiner").executeUpdate();
    s.createQuery("delete Vehicle").executeUpdate();

    t.commit();
    s.close();

    data.cleanup();
  }
  @Test
  public void testBridgeMapping() throws Exception {
    Address address = new Address();
    address.setStreet1("Peachtree Rd NE");
    address.setStreet2("JBoss");

    FullTextSession s = Search.getFullTextSession(openSession());
    Transaction tx = s.beginTransaction();
    s.persist(address);
    tx.commit();

    s.clear();

    tx = s.beginTransaction();

    QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer);
    org.apache.lucene.search.Query luceneQuery = parser.parse("street1:peac");
    FullTextQuery query = s.createFullTextQuery(luceneQuery);
    assertEquals("PrefixQuery should not be on", 0, query.getResultSize());

    luceneQuery = parser.parse("street1_abridged:peac");
    query = s.createFullTextQuery(luceneQuery);
    assertEquals("Bridge not used", 1, query.getResultSize());

    s.delete(query.list().get(0));
    tx.commit();
    s.close();
  }
  @Test
  public void testIncrementTimestampVersion() {
    Session s = openSession();
    Transaction t = s.beginTransaction();

    TimestampVersioned entity = new TimestampVersioned("ts-vers");
    s.save(entity);
    t.commit();
    s.close();

    Date initialVersion = entity.getVersion();

    synchronized (this) {
      try {
        wait(1500);
      } catch (InterruptedException ie) {
      }
    }

    s = openSession();
    t = s.beginTransaction();
    int count =
        s.createQuery("update versioned TimestampVersioned set name = name").executeUpdate();
    assertEquals("incorrect exec count", 1, count);
    t.commit();

    t = s.beginTransaction();
    entity = (TimestampVersioned) s.load(TimestampVersioned.class, entity.getId());
    assertTrue("version not incremented", entity.getVersion().after(initialVersion));

    s.delete(entity);
    t.commit();
    s.close();
  }
  @Test
  public void testMapping() throws Exception {
    Address address = new Address();
    address.setStreet1("3340 Peachtree Rd NE");
    address.setStreet2("JBoss");

    FullTextSession s = Search.getFullTextSession(openSession());
    Transaction tx = s.beginTransaction();
    s.persist(address);
    tx.commit();

    s.clear();

    tx = s.beginTransaction();

    QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer);
    org.apache.lucene.search.Query luceneQuery = parser.parse("" + address.getAddressId());
    FullTextQuery query = s.createFullTextQuery(luceneQuery);
    assertEquals("documentId does not work properly", 1, query.getResultSize());

    luceneQuery = parser.parse("street1:peachtree");
    query = s.createFullTextQuery(luceneQuery).setProjection("idx_street2", FullTextQuery.THIS);
    assertEquals("Not properly indexed", 1, query.getResultSize());
    Object[] firstResult = (Object[]) query.list().get(0);
    assertEquals("@Field.store not respected", "JBoss", firstResult[0]);

    // Verify that AddressClassBridge was applied as well:
    luceneQuery = parser.parse("AddressClassBridge:Applied\\!");
    assertEquals(1, s.createFullTextQuery(luceneQuery).getResultSize());

    s.delete(firstResult[1]);
    tx.commit();
    s.close();
  }
  /**
   * Tests that @DocumentId can be specified on a field other than the @Id annotated one. See
   * HSEARCH-574.
   *
   * @throws Exception in case the test fails.
   */
  @Test
  public void testExplicitDocumentIdMultipleResults() throws Exception {
    Article hello = new Article();
    hello.setDocumentId(1);
    hello.setText("Hello World");

    Article goodbye = new Article();
    goodbye.setDocumentId(2);
    goodbye.setText("Goodbye World");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.save(hello);
    s.save(goodbye);
    tx.commit();
    s.clear();

    tx = s.beginTransaction();
    List results =
        Search.getFullTextSession(s)
            .createFullTextQuery(new TermQuery(new Term("text", "world")))
            .list();
    assertEquals(2, results.size());
    tx.commit();
    s.close();
  }
  @Test
  public void testClassBridgeInstanceMapping() throws Exception {
    OrderLine orderLine = new OrderLine();
    orderLine.setName("Sequoia");

    FullTextSession s = Search.getFullTextSession(openSession());
    Transaction tx = s.beginTransaction();
    s.persist(orderLine);
    tx.commit();

    s.clear();

    tx = s.beginTransaction();

    QueryParser parser = new QueryParser("id", TestConstants.standardAnalyzer);
    org.apache.lucene.search.Query luceneQuery = parser.parse("orderLineName:Sequoia");
    FullTextQuery query = s.createFullTextQuery(luceneQuery);
    assertEquals("Bridge not used", 1, query.getResultSize());

    luceneQuery = parser.parse("orderLineName_ngram:quo");
    query = s.createFullTextQuery(luceneQuery);
    assertEquals("Analyzer configuration not applied", 1, query.getResultSize());

    luceneQuery = parser.parse("orderLineNameViaParam:Sequoia");
    query = s.createFullTextQuery(luceneQuery);
    assertEquals("Parameter configuration not applied", 1, query.getResultSize());

    s.delete(query.list().get(0));
    tx.commit();
    s.close();
  }
Esempio n. 29
0
  public void testDefaultConfigurationModeIsInherited() throws Exception {
    User john = new User();
    john.setFirstname("John");
    john.setLastname("Doe");
    List<User> friends = new ArrayList<User>();
    User friend = new User();
    friend.setFirstname("Jane");
    friend.setLastname("Doe");
    friends.add(friend);
    john.setFriends(friends);

    Session s = openSession();
    s.persist(john);
    Transaction tx = s.beginTransaction();
    tx.commit();
    s.clear();
    tx = s.beginTransaction();
    john = (User) s.get(User.class, john.getId());
    assertEquals("Wrong number of friends", 1, john.getFriends().size());
    assertNull(john.firstname);

    s.delete(john);
    tx.commit();
    s.close();
  }
  @Test(groups = "ch04")
  public void testEmbedded() throws Exception {
    Session session = factory.openSession();
    Item item = new Item();
    item.setDescription("Great DVD");
    item.setEan("123456789012");
    item.setTitle("Great DVD");
    item.setRating(new Rating());
    item.getRating().setOverall(5);
    item.getRating().setPicture(4);
    item.getRating().setScenario(5);
    item.getRating().setSoundtrack(3);
    Transaction tx = session.beginTransaction();
    session.save(item);
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    FullTextSession fts = Search.getFullTextSession(session);
    List results =
        fts.createFullTextQuery(new TermQuery(new Term("rating.overall", "5")), Item.class).list();
    assert results.size() == 1;
    fts.delete(results.get(0));
    tx.commit();
    fts.close();
  }