예제 #1
0
        public void Optimize()
        {
            IFullTextSession s  = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx = s.BeginTransaction();
            int loop            = 2000;

            for (int i = 0; i < loop; i++)
            {
                s.Persist(new Email(i + 1, "JBoss World Berlin", "Meet the guys who wrote the software"));
            }

            tx.Commit();
            s.Close();

            s  = Search.CreateFullTextSession(OpenSession());
            tx = s.BeginTransaction();
            s.SearchFactory.Optimize(typeof(Email));
            tx.Commit();
            s.Close();

            // Check non-indexed object get indexed by s.index;
            s  = new FullTextSessionImpl(OpenSession());
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "id", new StopAnalyzer(Environment.LuceneVersion));
            int         result = s.CreateFullTextQuery(parser.Parse("Body:wrote")).List().Count;

            Assert.AreEqual(2000, result);

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
        public void DoubleInsert()
        {
            Address address = new Address();

            address.Address1      = "TEST1";
            address.Address2      = "N/A";
            address.Town          = "TEST TOWN";
            address.County        = "TEST COUNTY";
            address.Country       = "UK";
            address.Postcode      = "XXXXXXX";
            address.Active        = true;
            address.CreatedOn     = DateTime.Now;
            address.LastUpdatedOn = DateTime.Now;

            Phone phone = new Phone();

            phone.Number        = "01273234122";
            phone.Type          = "HOME";
            phone.CreatedOn     = DateTime.Now;
            phone.LastUpdatedOn = DateTime.Now;

            PersonalContact contact = new PersonalContact();

            contact.Firstname   = "Amin";
            contact.Surname     = "Mohammed-Coleman";
            contact.Email       = "*****@*****.**";
            contact.DateOfBirth = DateTime.Now;

            // contact.NotifyBirthDay( false );
            contact.CreatedOn     = DateTime.Now;
            contact.LastUpdatedOn = DateTime.Now;
            contact.Notes         = "TEST";
            contact.AddAddressToContact(address);
            contact.AddPhoneToContact(phone);

            IFullTextSession s = Search.CreateFullTextSession(OpenSession());
            var tx             = s.BeginTransaction();

            s.Save(contact);
            tx.Commit();

            s.Close();

            s  = Search.CreateFullTextSession(OpenSession());
            tx = s.BeginTransaction();
            Term      term      = new Term("county", "county");
            TermQuery termQuery = new TermQuery(term);
            IList     results   = s.CreateFullTextQuery(termQuery).List();

            Assert.AreEqual(1, results.Count);
            s.Flush();
            s.Clear();

            s.Delete("from System.Object");
            tx.Commit();

            s.Close();
        }
예제 #3
0
        public void MultipleEntityPerIndex()
        {
            IFullTextSession s     = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx    = s.BeginTransaction();
            Clock            clock = new Clock(1, "Seiko");

            s.Save(clock);
            Book book =
                new Book(1, "La chute de la petite reine a travers les yeux de Festina",
                         "La chute de la petite reine a travers les yeux de Festina, blahblah");

            s.Save(book);
            AlternateBook alternateBook =
                new AlternateBook(1, "La chute de la petite reine a travers les yeux de Festina");

            s.Save(alternateBook);
            tx.Commit();
            s.Clear();
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "Title", new StopAnalyzer(Environment.LuceneVersion));

            Lucene.Net.Search.Query query = parser.Parse("Summary:Festina");
            IQuery hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            IList  result   = hibQuery.List();

            Assert.AreEqual(1, result.Count, "Query with explicit class filter");

            query    = parser.Parse("Summary:Festina");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            IEnumerator it = hibQuery.Enumerable().GetEnumerator();

            Assert.IsTrue(it.MoveNext());
            Assert.IsNotNull(it.Current);
            Assert.IsFalse(it.MoveNext());

            query    = parser.Parse("Summary:Festina OR Brand:seiko");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            hibQuery.SetMaxResults(2);
            result = hibQuery.List();
            Assert.AreEqual(2, result.Count, "Query with explicit class filter and limit");

            query    = parser.Parse("Summary:Festina");
            hibQuery = s.CreateFullTextQuery(query);
            result   = hibQuery.List();
            Assert.AreEqual(2, result.Count, "Query with no class filter");
            foreach (Object element in result)
            {
                Assert.IsTrue(NHibernateUtil.IsInitialized(element));
                s.Delete(element);
            }
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #4
0
        public void List()
        {
            IFullTextSession s     = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx    = s.BeginTransaction();
            Clock            clock = new Clock(1, "Seiko");

            s.Save(clock);
            clock = new Clock(2, "Festina");
            s.Save(clock);
            Book book =
                new Book(1, "La chute de la petite reine a travers les yeux de Festina",
                         "La chute de la petite reine a travers les yeux de Festina, blahblah");

            s.Save(book);
            book = new Book(2, "La gloire de mon père", "Les deboires de mon père en vélo");
            s.Save(book);
            tx.Commit();
            s.Clear();
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "title", new StopAnalyzer(Environment.LuceneVersion));

            Lucene.Net.Search.Query query = parser.Parse("Summary:noword");
            IQuery hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            IList  result   = hibQuery.List();

            Assert.AreEqual(0, result.Count);

            query    = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            result   = hibQuery.List();
            Assert.AreEqual(2, result.Count, "Query with explicit class filter");

            query    = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query);
            result   = hibQuery.List();
            Assert.AreEqual(2, result.Count, "Query with no class filter");
            foreach (Object element in result)
            {
                Assert.IsTrue(NHibernateUtil.IsInitialized(element));
                s.Delete(element);
            }
            s.Flush();
            tx.Commit();

            tx       = s.BeginTransaction();
            query    = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query);
            result   = hibQuery.List();
            Assert.AreEqual(0, result.Count, "Query with delete objects");

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #5
0
        public void FirstMax()
        {
            ISession sess = OpenSession();

            Assert.AreEqual(0, sess.CreateCriteria(typeof(Clock)).List().Count);

            IFullTextSession s     = Search.CreateFullTextSession(sess);
            ITransaction     tx    = s.BeginTransaction();
            Clock            clock = new Clock(1, "Seiko");

            s.Save(clock);
            clock = new Clock(2, "Festina");
            s.Save(clock);
            Book book =
                new Book(1, "La chute de la petite reine a travers les yeux de Festina",
                         "La chute de la petite reine a travers les yeux de Festina, blahblah");

            s.Save(book);
            book = new Book(2, "La gloire de mon père", "Les deboires de mon père en vélo");
            s.Save(book);
            tx.Commit();
            s.Clear();
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "title", new StopAnalyzer(Environment.LuceneVersion));

            Lucene.Net.Search.Query query = parser.Parse("Summary:Festina Or Brand:Seiko");
            IQuery hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));

            hibQuery.SetFirstResult(1);
            IList result = hibQuery.List();

            Assert.AreEqual(1, result.Count, "first result no max result");

            hibQuery.SetFirstResult(0);
            hibQuery.SetMaxResults(1);
            result = hibQuery.List();
            Assert.AreEqual(1, result.Count, "max result set");

            hibQuery.SetFirstResult(0);
            hibQuery.SetMaxResults(3);
            result = hibQuery.List();
            Assert.AreEqual(2, result.Count, "max result out of limit");

            hibQuery.SetFirstResult(2);
            hibQuery.SetMaxResults(3);
            result = hibQuery.List();
            Assert.AreEqual(0, result.Count, "first result out of limit");

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #6
0
        public void Iterator()
        {
            IFullTextSession s     = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx    = s.BeginTransaction();
            Clock            clock = new Clock(1, "Seiko");

            s.Save(clock);
            clock = new Clock(2, "Festina");
            s.Save(clock);
            Book book =
                new Book(1, "La chute de la petite reine a travers les yeux de Festina",
                         "La chute de la petite reine a travers les yeux de Festina, blahblah");

            s.Save(book);
            book = new Book(2, "La gloire de mon père", "Les deboires de mon père en vélo");
            s.Save(book);
            tx.Commit(); //post Commit events for lucene
            s.Clear();
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "title", new StopAnalyzer(Environment.LuceneVersion));

            Lucene.Net.Search.Query query = parser.Parse("Summary:noword");
            IQuery      hibQuery          = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            IEnumerator result            = hibQuery.Enumerable().GetEnumerator();

            Assert.IsFalse(result.MoveNext());

            query    = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            result   = hibQuery.Enumerable().GetEnumerator();
            int index = 0;

            while (result.MoveNext())
            {
                index++;
                s.Delete(result.Current);
            }
            Assert.AreEqual(2, index);

            tx.Commit();

            tx       = s.BeginTransaction();
            query    = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            result   = hibQuery.Enumerable().GetEnumerator();

            Assert.IsFalse(result.MoveNext());
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
        public void ResultTransformToDelimString()
        {
            IFullTextSession s = Search.CreateFullTextSession(this.OpenSession());

            this.PrepEmployeeIndex(s);

            s.Clear();
            ITransaction tx     = s.BeginTransaction();
            QueryParser  parser = new QueryParser(NHibernate.Search.Environment.LuceneVersion, "Dept", new StandardAnalyzer(NHibernate.Search.Environment.LuceneVersion));

            Query          query    = parser.Parse("Dept:ITech");
            IFullTextQuery hibQuery = s.CreateFullTextQuery(query, typeof(Employee));

            hibQuery.SetProjection(
                "Id",
                "Lastname",
                "Dept",
                ProjectionConstants.THIS,
                ProjectionConstants.SCORE,
                ProjectionConstants.BOOST,
                ProjectionConstants.ID);
            hibQuery.SetResultTransformer(new ProjectionToDelimStringResultTransformer());

            IList result = hibQuery.List();

            Assert.IsTrue(((string)result[0]).StartsWith("1000, Griffin, ITech"), "incorrect transformation");
            Assert.IsTrue(((string)result[1]).StartsWith("1002, Jimenez, ITech"), "incorrect transformation");

            // cleanup
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #8
0
        public IList <TaskMainDAO> Find(string textQuery)
        {
            if (textQuery == string.Empty)
            {
                return(null);
            }
            ISessionFactory applicationFactory = NhibernateSessionFactory.GetSessionFactory(NhibernateSessionFactory.SessionFactoryConfiguration.Application);

            using (ISession session = applicationFactory.OpenSession())
                using (IFullTextSession fullTextSession = Search.CreateFullTextSession(session))
                    using (ITransaction transaction = fullTextSession.BeginTransaction())
                    {
                        try
                        {
                            IFullTextQuery      fullTextQuery = fullTextSession.CreateFullTextQuery <TaskMainDAO>(textQuery);
                            IList <TaskMainDAO> tasks         = fullTextQuery.List <TaskMainDAO>();
                            transaction.Commit();
                            return(tasks);
                        }
                        catch (Lucene.Net.QueryParsers.ParseException e)
                        {
                            //handle parsing failure. Display some indication like "Wrong search criteria"
                            transaction.Commit();
                            return(new TaskMainDAO[0]);
                        }
                    }
        }
예제 #9
0
        private static void FillDb()
        {
            using (IFullTextSession s = Search.CreateFullTextSession(sf.OpenSession())) {
                using (ITransaction tx = s.BeginTransaction()){
                    Book b1 = new Book(1,
                                       "Eric Evans",
                                       "Domain-Driven Design: Tackling Complexity in the Heart of Software",
                                       "This book provides a broad framework for making design decisions and a technical vocabulary for discussing domain design. It is a synthesis of widely accepted best practices along with the author's own insights and experiences."
                                       );

                    s.Save(b1);

                    Book b2 = new Book(2,
                                       "Pierre Kuate",
                                       "NHibernate in Action",
                                       "In the classic style of Manning's 'In Action' series, NHibernate in Action introduces .NET developers to the NHibernate Object/Relational Mapping tool. As NHibernate is a port of Hibernate from Java to .NET.");
                    s.Save(b2);

                    Book b3 = new Book(3,
                                       "John Doe",
                                       "Foo book NHibernate",
                                       "Foo series book");
                    s.Save(b3);

                    s.Flush();
                    tx.Commit();
                }
            }
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="s"></param>
        private void DeleteTestBooks(IFullTextSession s)
        {
            ITransaction tx = s.BeginTransaction();

            s.Delete("from System.Object");
            tx.Commit();
            s.Clear();
        }
예제 #11
0
        public void PurgeAll()
        {
            IFullTextSession s     = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx    = s.BeginTransaction();
            Clock            clock = new Clock(1, "Seiko");

            s.Save(clock);
            clock = new Clock(2, "Festina");
            s.Save(clock);
            clock = new Clock(3, "Longine");
            s.Save(clock);
            clock = new Clock(4, "Rolex");
            s.Save(clock);
            Book book = new Book(1, "La chute de la petite reine a travers les yeux de Festina", "La chute de la petite reine a travers les yeux de Festina, blahblah");

            s.Save(book);
            book = new Book(2, "La gloire de mon père", "Les deboires de mon père en vélo");
            s.Save(book);
            tx.Commit();
            s.Clear();

            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "Brand", new StopAnalyzer(Environment.LuceneVersion));

            tx = s.BeginTransaction();
            s.PurgeAll(typeof(Clock));

            tx.Commit();

            tx = s.BeginTransaction();

            Lucene.Net.Search.Query query = parser.Parse("Brand:Festina or Brand:Seiko or Brand:Longine or Brand:Rolex");
            IQuery hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            IList  results  = hibQuery.List();

            Assert.AreEqual(0, results.Count, "class not completely purged");

            query    = parser.Parse("Summary:Festina or Summary:gloire");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            results  = hibQuery.List();
            Assert.AreEqual(2, results.Count, "incorrect class purged");

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
        public void ProxyObjectInheritance()
        {
            // This will test subclassed proxy objects and make sure that they are index correctly.
            IFullTextSession s  = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx = s.BeginTransaction();

            // Create an object in db
            Mammal temp = new Mammal();

            temp.NumberOfLegs = (4);
            temp.Name         = ("Some Mammal Name Here");
            s.Save(temp);

            tx.Commit(); //post commit events for lucene

            // Clear object from cache by clearing session
            s.Clear();

            // This should return a proxied object
            Mammal mammal = s.Load <Mammal>(temp.Id);

            // Index the proxied object
            s.Index(mammal);

            // Build an index reader
            var reader = s.SearchFactory.ReaderProvider.OpenReader(s.SearchFactory.GetDirectoryProviders(typeof(Mammal)));

            // Get the last document indexed
            var Document = reader.Document(reader.MaxDoc() - 1);

            // get the class name field from the document
            string classTypeThatWasIndex = Document.Get(NHibernate.Search.Engine.DocumentBuilder.CLASS_FIELDNAME);

            // get the expected lucene type name (this should be equivilent to
            // the static method of NHibernate.Search.Util.TypeHelper.LuceneTypeName
            string expectedLuceneTypeName = typeof(Mammal).FullName + ", " + typeof(Mammal).Assembly.GetName().Name;

            Assert.AreEqual(expectedLuceneTypeName, classTypeThatWasIndex);

            // Tidyup
            tx = s.BeginTransaction();
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #13
0
        public void Inheritance()
        {
            IFullTextSession s  = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx = s.BeginTransaction();
            Animal           a  = new Animal();

            a.Name = ("Shark Jr");
            s.Save(a);
            Mammal m = new Mammal();

            m.NumberOfLegs = (4);
            m.Name         = ("Elephant Jr");
            s.Save(m);
            tx.Commit(); //post commit events for lucene
            s.Clear();
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "Name", new StopAnalyzer(Environment.LuceneVersion));

            Lucene.Net.Search.Query query = parser.Parse("Elephant");
            IQuery hibQuery = s.CreateFullTextQuery(query, typeof(Mammal));
            IList  result   = hibQuery.List();

            Assert.IsNotEmpty(result);
            Assert.AreEqual(1, result.Count, "Query subclass by superclass attribute");

            query    = parser.Parse("NumberOfLegs:[4 TO 4]");
            hibQuery = s.CreateFullTextQuery(query, typeof(Animal), typeof(Mammal));
            result   = hibQuery.List();
            Assert.IsNotEmpty(result);
            Assert.AreEqual(1, result.Count, "Query subclass by subclass attribute");

            query    = parser.Parse("Jr");
            hibQuery = s.CreateFullTextQuery(query, typeof(Animal));
            result   = hibQuery.List();
            Assert.IsNotEmpty(result);
            Assert.AreEqual(2, result.Count, "Query filtering on superclass return mapped subclasses");
            foreach (Object managedEntity in result)
            {
                s.Delete(managedEntity);
            }
            tx.Commit();
            s.Close();
        }
예제 #14
0
        public void TestScopedAnalyzers()
        {
            MyEntity en = new MyEntity();

            en.Entity    = "Entity";
            en.Field     = "Field";
            en.Property  = "Property";
            en.Component = new MyComponent();
            en.Component.ComponentProperty = "component property";

            IFullTextSession s  = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx = s.BeginTransaction();

            s.Save(en);
            s.Flush();
            tx.Commit();

            tx = s.BeginTransaction();

            QueryParser parser = new QueryParser("id", new StandardAnalyzer());

            Lucene.Net.Search.Query luceneQuery = parser.Parse("entity:alarm");
            IFullTextQuery          query       = s.CreateFullTextQuery(luceneQuery, typeof(MyEntity));

            Assert.AreEqual(1, query.ResultSize, "Entity query");

            luceneQuery = parser.Parse("property:cat");
            query       = s.CreateFullTextQuery(luceneQuery, typeof(MyEntity));
            Assert.AreEqual(1, query.ResultSize, "Property query");

            luceneQuery = parser.Parse("field:energy");
            query       = s.CreateFullTextQuery(luceneQuery, typeof(MyEntity));
            Assert.AreEqual(1, query.ResultSize, "Field query");

            luceneQuery = parser.Parse("component.componentProperty:noise");
            query       = s.CreateFullTextQuery(luceneQuery);
            Assert.AreEqual(1, query.ResultSize, "Component query");

            s.Delete(query.UniqueResult());
            tx.Commit();

            s.Close();
        }
예제 #15
0
        public void Purge()
        {
            IFullTextSession s     = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx    = s.BeginTransaction();
            Clock            clock = new Clock(1, "Seiko");

            s.Save(clock);
            clock = new Clock(2, "Festina");
            s.Save(clock);
            Book book = new Book(1, "La chute de la petite reine a travers les yeux de Festina", "La chute de la petite reine a travers les yeux de Festina, blahblah");

            s.Save(book);
            book = new Book(2, "La gloire de mon père", "Les deboires de mon père en vélo");
            s.Save(book);
            tx.Commit();
            s.Clear();

            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser("Brand", new StopAnalyzer());

            Lucene.Net.Search.Query query = parser.Parse("Brand:Seiko");
            IQuery hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            IList  results  = hibQuery.List();

            Assert.AreEqual(1, results.Count, "incorrect test record");
            Assert.AreEqual(1, ((Clock)results[0]).Id, "incorrect test record");

            s.Purge(typeof(Clock), ((Clock)results[0]).Id);

            tx.Commit();

            tx = s.BeginTransaction();

            query    = parser.Parse("Brand:Festina or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            results  = hibQuery.List();
            Assert.AreEqual(1, results.Count, "incorrect test record count");
            Assert.AreEqual(2, ((Clock)results[0]).Id, "incorrect test record");

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #16
0
        public void GenerateIndexes()
        {
            ISessionFactory applicationFactory = NhibernateSessionFactory.GetSessionFactory(NhibernateSessionFactory.SessionFactoryConfiguration.Application);

            using (ISession session = applicationFactory.OpenSession())
                using (IFullTextSession fullTextSession = Search.CreateFullTextSession(session))
                {
                    using (ITransaction transaction = fullTextSession.BeginTransaction())
                    {
                        fullTextSession.PurgeAll(typeof(TaskMainDAO));
                        transaction.Commit();
                    }
                    using (ITransaction transaction = fullTextSession.BeginTransaction())
                    {
                        foreach (object entity in fullTextSession.CreateCriteria(typeof(TaskMainDAO)).List())
                        {
                            fullTextSession.Index(entity);
                        }
                        transaction.Commit();
                    }
                }
        }
예제 #17
0
        public void Criteria()
        {
            IFullTextSession s    = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx   = s.BeginTransaction();
            Book             book = new Book(1, "La chute de la petite reine a travers les yeux de Festina", "La chute de la petite reine a travers les yeux de Festina, blahblah");

            s.Save(book);
            Author emmanuel = new Author();

            emmanuel.Name = "Emmanuel";
            s.Save(emmanuel);
            book.Authors.Add(emmanuel);
            tx.Commit();
            s.Clear();

            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "Title", new StopAnalyzer(Environment.LuceneVersion));

            Lucene.Net.Search.Query query    = parser.Parse("Summary:Festina");
            IFullTextQuery          hibQuery = s.CreateFullTextQuery(query, typeof(Book));
            IList result = hibQuery.List();

            Assert.NotNull(result);
            Assert.AreEqual(1, result.Count, "Query with no explicit criteria");
            book = (Book)result[0];
            //Assert.IsFalse(NHibernate.IsInitialized(book.Authors), "Association should not be initialized");

            result = s.CreateFullTextQuery(query).SetCriteriaQuery(s.CreateCriteria(typeof(Book)).SetFetchMode("Authors", FetchMode.Join)).List();
            Assert.NotNull(result);
            Assert.AreEqual(1, result.Count, "Query with no explicit criteria");
            book = (Book)result[0];
            //Assert.IsTrue(NHibernate.IsInitialized(book.Authors), "Association should be initialized");
            Assert.AreEqual(1, book.Authors.Count);

            // cleanup
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #18
0
        public void BatchSize()
        {
            IFullTextSession s  = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx = s.BeginTransaction();
            int loop            = 14;

            for (int i = 0; i < loop; i++)
            {
                using (IDbCommand cmd = s.Connection.CreateCommand())
                {
                    s.Transaction.Enlist(cmd);
                    cmd.CommandText = "insert into Email(Id, Title, Body, Header) values( + " + (i + 1)
                                      + ", 'Bob Sponge', 'Meet the guys who create the software', 'nope')";
                    cmd.ExecuteNonQuery();
                }
            }
            tx.Commit();
            s.Close();

            s  = new FullTextSessionImpl(OpenSession());
            tx = s.BeginTransaction();
            int index = 0;

            foreach (object entity in s.CreateCriteria(typeof(Email)).List())
            {
                index++;
                s.Index(entity);

                // NB Java uses a scrollable result, so clear works for them, but not for us I think
                //if (index % 5 == 0)
                //{
                //    s.Clear();
                //}
            }
            tx.Commit();
            s.Clear();

            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser("id", new StopAnalyzer());
            IList       result = s.CreateFullTextQuery(parser.Parse("Body:create")).List();

            Assert.AreEqual(14, result.Count);

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
        public void LuceneObjectsProjectionWithIterate()
        {
            IFullTextSession s = Search.CreateFullTextSession(this.OpenSession());

            this.PrepEmployeeIndex(s);

            s.Clear();
            ITransaction tx     = s.BeginTransaction();
            QueryParser  parser = new QueryParser(NHibernate.Search.Environment.LuceneVersion, "Dept", new StandardAnalyzer(NHibernate.Search.Environment.LuceneVersion));

            Query          query    = parser.Parse("Dept:ITech");
            IFullTextQuery hibQuery = s.CreateFullTextQuery(query, typeof(Employee));

            hibQuery.SetProjection(
                "Id",
                "Lastname",
                "Dept",
                ProjectionConstants.THIS,
                ProjectionConstants.SCORE,
                ProjectionConstants.BOOST,
                ProjectionConstants.DOCUMENT,
                ProjectionConstants.ID);

            int counter = 0;

            foreach (object[] projection in hibQuery.Enumerable())
            {
                Assert.IsNotNull(projection);
                counter++;
                Assert.AreEqual("ITech", projection[2], "dept incorrect");
                Assert.AreEqual(projection[3], s.Get <Employee>(projection[0]), "THIS incorrect");
                Assert.AreEqual(1.0F, projection[4], "SCORE incorrect");
                Assert.AreEqual(1.0F, projection[5], "BOOST incorrect");
                Assert.IsTrue(projection[6] is Document, "DOCUMENT incorrect");
                Assert.AreEqual(4, ((Document)projection[6]).GetFields().Count, "DOCUMENT size incorrect");
            }
            Assert.AreEqual(4, counter, "incorrect number of results returned");

            // cleanup
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #20
0
        public void UsingCriteriaApi()
        {
            IFullTextSession s     = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx    = s.BeginTransaction();
            Clock            clock = new Clock(1, "Seiko");

            s.Save(clock);
            tx.Commit();

            IList list = s.CreateFullTextQuery <Clock>("Brand:seiko")
                         .SetCriteriaQuery(s.CreateCriteria(typeof(Clock)).Add(Restrictions.IdEq(1)))
                         .List();

            Assert.AreEqual(1, list.Count, "should get result back from query");

            s.Delete(clock);
            s.Flush();
            s.Close();
        }
예제 #21
0
        /// <summary>
        /// Helper method creating three books with the same title and summary.
        /// When searching for these books the results should be returned in the order
        /// they got added to the index.
        /// </summary>
        /// <param name="s">The full text session used to index the test data.</param>
        private void CreateTestBooks(IFullTextSession s)
        {
            ITransaction tx   = s.BeginTransaction();
            DateTime     cal  = new DateTime(2007, 07, 25, 11, 20, 30);
            Book         book = new Book(1, "Hibernate & Lucene", "This is a test book.");

            book.PublicationDate = cal;
            s.Save(book);
            book = new Book(2, "Hibernate & Lucene", "This is a test book.");
            book.PublicationDate = cal.AddSeconds(1);
            s.Save(book);
            book = new Book(3, "Hibernate & Lucene", "This is a test book.");
            book.PublicationDate = cal.AddSeconds(2);
            s.Save(book);
            book = new Book(4, "Groovy in Action", "The bible of Groovy");
            book.PublicationDate = cal.AddSeconds(3);
            s.Save(book);
            tx.Commit();
            s.Clear();
        }
        private void PrepEmployeeIndex(IFullTextSession s)
        {
            ITransaction tx = s.BeginTransaction();
            Employee     e1 = new Employee(1000, "Griffin", "ITech");

            s.Save(e1);
            Employee e2 = new Employee(1001, "Jackson", "Accounting");

            s.Save(e2);
            Employee e3 = new Employee(1002, "Jimenez", "ITech");

            s.Save(e3);
            Employee e4 = new Employee(1003, "Stejskal", "ITech");

            s.Save(e4);
            Employee e5 = new Employee(1004, "Whetbrook", "ITech");

            s.Save(e5);

            tx.Commit();
        }
        public void ResultTransformMap()
        {
            IFullTextSession s = Search.CreateFullTextSession(this.OpenSession());

            this.PrepEmployeeIndex(s);

            s.Clear();
            ITransaction tx     = s.BeginTransaction();
            QueryParser  parser = new QueryParser(NHibernate.Search.Environment.LuceneVersion, "Dept", new StandardAnalyzer(NHibernate.Search.Environment.LuceneVersion));

            Query          query    = parser.Parse("Dept:ITech");
            IFullTextQuery hibQuery = s.CreateFullTextQuery(query, typeof(Employee));

            hibQuery.SetProjection(
                "Id",
                "Lastname",
                "Dept",
                ProjectionConstants.THIS,
                ProjectionConstants.SCORE,
                ProjectionConstants.BOOST,
                ProjectionConstants.DOCUMENT,
                ProjectionConstants.ID);
            hibQuery.SetResultTransformer(new ProjectionToMapResultTransformer());

            IList transforms = hibQuery.List();
            Dictionary <string, object> map = (Dictionary <string, object>)transforms[1];

            Assert.AreEqual("ITech", map["Dept"], "incorrect transformation");
            Assert.AreEqual(1002, map["Id"], "incorrect transformation");
            Assert.IsTrue(map[ProjectionConstants.DOCUMENT] is Document, "incorrect transformation");
            Assert.AreEqual(
                "1002",
                ((Document)map[ProjectionConstants.DOCUMENT]).GetField("Id").StringValue,
                "incorrect transformation");

            // cleanup
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
예제 #24
0
        public void Fields()
        {
            Document doc = new Document(
                "Hibernate in Action", "Object/relational mapping with Hibernate", "blah blah blah");
            ISession     s  = this.OpenSession();
            ITransaction tx = s.BeginTransaction();

            s.Save(doc);
            tx.Commit();

            s.Clear();

            IFullTextSession session = Search.CreateFullTextSession(s);

            tx = session.BeginTransaction();
            QueryParser p      = new QueryParser("id", new StandardAnalyzer());
            IList       result = session.CreateFullTextQuery(p.Parse("Abstract:Hibernate")).List();

            Assert.AreEqual(1, result.Count, "Query by field");
            s.Delete(result[0]);
            tx.Commit();
            s.Close();
        }
예제 #25
0
        public void ObjectNotFound()
        {
            ISession     sess = OpenSession();
            ITransaction tx   = sess.BeginTransaction();

            Author author = new Author();

            author.Name = "Moo Cow";
            sess.Persist(author);

            tx.Commit();
            sess.Clear();
            IDbCommand statement = sess.Connection.CreateCommand();

            statement.CommandText = "DELETE FROM Author";
            statement.ExecuteNonQuery();

            IFullTextSession s = Search.CreateFullTextSession(sess);

            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(LuceneVersion.LUCENE_48, "title", new KeywordAnalyzer());

            Lucene.Net.Search.Query query    = parser.Parse("name:moo");
            IFullTextQuery          hibQuery = s.CreateFullTextQuery(query, typeof(Author), typeof(Music));
            IList result = hibQuery.List();

            Assert.AreEqual(0, result.Count, "Should have returned no author");

            foreach (object o in result)
            {
                s.Delete(o);
            }

            tx.Commit();
            s.Close();
        }
예제 #26
0
        public void FieldBoost()
        {
            ISession     s  = this.OpenSession();
            ITransaction tx = s.BeginTransaction();

            s.Save(new Document("Hibernate in Action", "Object and Relational", "blah blah blah"));
            s.Save(new Document("Object and Relational", "Hibernate in Action", "blah blah blah"));
            tx.Commit();

            s.Clear();

            IFullTextSession session = Search.CreateFullTextSession(s);

            tx = session.BeginTransaction();
            QueryParser p      = new QueryParser("id", new StandardAnalyzer());
            IList       result = session.CreateFullTextQuery(p.Parse("title:Action OR Abstract:Action")).List();

            Assert.AreEqual(2, result.Count, "Query by field");
            Assert.AreEqual("Hibernate in Action", ((Document)result[0]).Title, "@Boost fails");
            s.Delete(result[0]);
            s.Delete(result[1]);
            tx.Commit();
            s.Close();
        }
예제 #27
0
        private void BuildBooksCatalog()
        {
            log.Debug("Creating sample books");

            using (new TemporaryOffLog("NHibernate.SQL"))
                using (IFullTextSession s = NHibernate.Search.Search.CreateFullTextSession(OpenSession(new SearchInterceptor())))
                    using (ITransaction trans = s.BeginTransaction())
                    {
                        s.Save(new Book("NHibernate in Action", "Pierre Henri Kuaté",
                                        @"NHibernate practically exploded on the .NET scene. Why is this open-source tool so popular? Because it automates a tedious task: persisting your .NET objects to a relational database. The inevitable mismatch between your object-oriented code and the relational database requires you to write code that maps one to the other. This code is often complex, tedious and costly to develop. NHibernate does the mapping for you.
								Not only that, NHibernate makes it easy. Positioned as a layer between your application and your database, NHibernate takes care of loading and saving of objects. NHibernate applications are cheaper, more portable, and more resilient to change. And they perform better than anything you are likely to develop yourself.
								NHibernate in Action carefully explains the concepts you need, then gets you going. It builds on a single example to show you how to use NHibernate in practice, how to deal with concurrency and transactions, how to efficiently retrieve objects and use caching.
								The authors created NHibernate and they field questions from the NHibernate community every day–they know how to make NHibernate sing. Knowledge and insight seep out of every pore of this book.
								What's Inside
								- ORM concepts
								- Getting started
								- Many real-world tasks
								- The NHibernate application development process"                                ));

                        s.Save(new Book("Beginning Hibernate: From Novice to Professional", "Dave Minter",
                                        @"“[This] is a book about design in the .NET world, driven in an agile manner and infused with the products of the enterprise patterns community. [It] shows you how to begin applying such things as TDD, object relational mapping, and DDD to .NET projects...techniques that many developers think are the key to future software development.... As the technology gets more capable and sophisticated, it becomes more important to understand how to use it well. This book is a valuable step toward advancing that understanding.”
								– Martin Fowler, author of Refactoring and Patterns of Enterprise Application Architecture
								Patterns, Domain-Driven Design (DDD), and Test-Driven Development (TDD) enable architects and developers to create systems that are powerful, robust, and maintainable. Now, there’s a comprehensive, practical guide to leveraging all these techniques primarily in Microsoft .NET environments, but the discussions are just as useful for Java developers. 
								Drawing on seminal work by Martin Fowler (Patterns of Enterprise Application Architecture) and Eric Evans (Domain-Driven Design), Jimmy Nilsson shows how to create real-world architectures for any .NET application. Nilsson illuminates each principle with clear, well-annotated code examples based on C# 1.1 and 2.0. His examples and discussions will be valuable both to C# developers and those working with other .NET languages and any databases–even with other platforms, such as J2EE. Coverage includes 
								- Quick primers on patterns, TDD, and refactoring
								- Using architectural techniques to improve software quality
								- Using domain models to support business rules and validation
								- Applying enterprise patterns to provide persistence support via NHibernate
								- Planning effectively for the presentation layer and UI testing
								- Designing for Dependency Injection, Aspect Orientation, and other new paradigms."                                ));

                        s.Save(new Book("Applying Domain-Driven Design and Patterns: With Examples in C# and .NET", "Jimmy Nilsson",
                                        @"Beginning Hibernate is ideal if you're experienced in Java with databases (the traditional, or ""connected,"" approach), but are new to open source lightweight Hibernate&emdash;the most popular de facto object-relational mapping and database-oriented application development framework. This book packs in brand new information about the latest release of the Hibernate 3.2.x persistence layer and provides a clear introduction to the current standard for object-relational persistence in Java.
								Experienced author Dave Minter and contributor Jeff Linwood provide more in-depth examples than any other books for Hibernate beginners. The authors also present material in a lively, example-based manner&emdash;not in a dry, theoretical, hard-to-read fashion. And since the book keeps its focus on Hibernate without wasting time on nonessential third-party tools, you'll be able to immediately start building transaction-based engines and applications."                                ));

                        s.Save(new Book("Open Source .NET Development: Programming with NAnt, NUnit, NDoc, and More", "Brian Nantz",
                                        @"Perhaps the most revolutionary aspect of the arrival of Microsoft's .NET platform is the standardization of C# and the Common Language Runtime. Now, for the first time, programmers can develop and use open-source projects that are based on a language that is an international standard as well as compatible with both Microsoft and Linux platforms. 
								Open Source .NET Development is the definitive guide on .NET development in an open-source environment
								Inside, readers will find in-depth information on using NAnt, NDoc, NUnit, Draco.NET, log4net, and Aspell.Net with both Visual Studio .NET and the Mono Project. Brian Nantz not only shares the best open-source and ""free"" tools, frameworks, components, and products for .NET, he also provides usable, practical examples and projects. The result is a highly accessible reference for finding the tools that best fit your needs.

								Highlights include
								- An introduction to open source and its implementations of the .NET standards 
								- .NET development with open-source tools, including build automation, XML documentation, unit testing, continuous integration, and application logging 
								- A simple example of Integrating .NET open-source projects that integrates an Open Source SVG component with a System.Drawing graphical editor 
								- An Aspell.Net case study that shows the use of Draco.NET Continuous Integration in conjunction with NAnt, NUnit, NDoc, and the SharpDevelop IDE 
								- An exclusive look at ADO.NET database and ASP.NET Web development using PostgreSQL that runs on both Windows and Linux 
								- Appendixes on NAnt and NAntContrib tasks, log4netAppender configurations, and open-source security observations 
								- Whether you are a .NET developer interested in learning more about open-source tools or an open-source developer curious about .NET, this book will bridge the divide between these formerly distinct camps."                                ));

                        s.Save(new Book("Practical Software Factories in .NET", "Gunther Lenz",
                                        @"The promise of Software Factories is to streamline and automate software development-and thus to produce higher-quality software more efficiently. The key idea is to promote systematic reuse at all levels and exploit economies of scope, which translates into concrete savings in planning, development, and maintenance efforts. However, the theory behind Software Factories can be overwhelming, because it spans many disciplines of software development. On top of that, Software Factories typically require significant investments into reusable assets.
								This book was written in order to demystify the Software Factories paradigm by guiding you through a practical case study from the early conception phase of building a Software Factory to delivering a ready-made software product. The authors provide you with a hands-on example covering each of the four pillars of Software Factories: software product lines, architectural frameworks, model-driven development, and guidance in context.
								While the ideas behind Software Factories are platform independent, the Microsoft .NET platform, together with recent technologies such as DSL Tools and the Smart Client Baseline Architecture Toolkit, makes an ideal foundation. A study shows the different facets and caveats and demonstrates how each of these technologies becomes part of a comprehensive factory. Software Factories are a top candidate for revolutionizing software development. This book will give you a great starting point to understanding the concepts behind it and ultimately applying this knowledge to your own software projects.
								Contributions by Jack Greenfield, Wojtek Kozaczynski Foreword by Douglas C. Schmidt, Jack Greenfield, Jürgen Kazmeier and Eugenio Pace."                                ));

                        s.Save(new Book("LINQ in Action", "Fabrice Marguerie",
                                        @"LLINQ, Language INtegrated Query, is a new extension to the Visual Basic and C# programming languages designed to simplify data queries and database interaction. It addreses O/R mapping issues by making query operations like SQL statements part of the programming language. It also offers built-in support for querying in-memory collections like arrays or lists, XML, DataSets, and relational databases. 
								LINQ in Action is a fast-paced, comprehensive tutorial for professional developers. This book explores what can be done with LINQ, shows how it works in an application, and addresses the emerging best practices. It presents the general purpose query facilities offered by LINQ in the upcoming C# 3.0 and VB.NET 9.0 languages. A running example introduces basic LINQ concepts. You'll then learn to query unstructured data using LINQ to XML and relational data with LINQ to SQL. Finally, you'll see how to extend LINQ for custom applications. 
								LINQ in Action will guide you along as you explore this new world of lambda expressions, query operators, and expression trees. As well, you'll explore the new features of C# 3.0, VB.NET 9.0. The book is very practical, anchoring each new idea with running code. Whether you want to use LINQ to query objects, XML documents, or relational databases, you will find all the information you need to get started 
								But LINQ in Action does not stop at the basic code. This book also shows you how LINQ can be used for advanced processing of data, including coverage of LINQ's extensibility, which allows querying more data sources than those supported by default. All code samples are built on a concrete business case. The running example, LinqBooks, is a personal book cataloging system that shows you how to create LINQ applications with Visual Studio 2008."                                ));

                        s.Save(new Book("ASP.NET 3.5 Unleashed", "Stephen Walther",
                                        @"ASP.NET 3.5 Unleashed is the most comprehensive book available on the Microsoft ASP.NET 3.5 Framework, covering all aspects of the ASP.NET 3.5 Framework--no matter how advanced.
								This edition covers all the new features of ASP.NET 3.5. It explains Microsoft LINQ to SQL in detail. It includes a chapter on the two new data access controls introduced with the ASP.NET 3.5 Framework: ListView and DataPager. With its coverage of ASP.NET AJAX, this book shows you how to take advantage of Microsoft’s server-side AJAX framework to retrofit existing ASP.NET applications with AJAX functionality. It also demonstrates how to use Microsoft’s client-side AJAX framework to build the web applications of the future: pure client-side AJAX applications. All code samples are written in the C# programming language. (Visual Basic versions of all code samples are included on the CD-ROM that accompanies this book.)
								Take advantage of Microsoft’s new database query language, LINQ to SQL, to easily build database-driven web applications 
								Learn how to use the new ListView and DataPager data access controls to build flexible user interfaces 
								- Take advantage of ASP.NET AJAX when building both server-side and client-side web applications 
								- Use the AJAX Control Toolkit to create auto-complete text fields, draggable panels, masked edit fields, and complex animations 
								- Design ASP.NET websites 
								- Secure your ASP.NET applications 
								- Create custom components 
								- Build highly interactive websites that can scale to handle thousands of simultaneous users 
								- Learn to build a complete ASP.NET 3.5 website from start to finish–the last chapter of the book includes a sample ASP.NET 3.5 web application written with LINQ to SQL and ASP.NET AJAX
								CD-ROM includes all examples and source code presented in this book in both C# and Visual Basic."                                ));

                        trans.Commit();
                    }
        }
        private void PrepEmployeeIndex(IFullTextSession s)
        {
            ITransaction tx = s.BeginTransaction();
            Employee e1 = new Employee(1000, "Griffin", "ITech");
            s.Save(e1);
            Employee e2 = new Employee(1001, "Jackson", "Accounting");
            s.Save(e2);
            Employee e3 = new Employee(1002, "Jimenez", "ITech");
            s.Save(e3);
            Employee e4 = new Employee(1003, "Stejskal", "ITech");
            s.Save(e4);
            Employee e5 = new Employee(1004, "Whetbrook", "ITech");
            s.Save(e5);

            tx.Commit();
        }
 /// <summary>
 /// Helper method creating three books with the same title and summary.
 /// When searching for these books the results should be returned in the order
 /// they got added to the index.
 /// </summary>
 /// <param name="s">The full text session used to index the test data.</param>
 private void CreateTestBooks(IFullTextSession s)
 {
     ITransaction tx = s.BeginTransaction();
     DateTime cal = new DateTime(2007, 07, 25, 11, 20, 30);
     Book book = new Book(1, "Hibernate & Lucene", "This is a test book.");
     book.PublicationDate = cal;
     s.Save(book);
     book = new Book(2, "Hibernate & Lucene", "This is a test book.");
     book.PublicationDate = cal.AddSeconds(1);
     s.Save(book);
     book = new Book(3, "Hibernate & Lucene", "This is a test book.");
     book.PublicationDate = cal.AddSeconds(2);
     s.Save(book);
     book = new Book(4, "Groovy in Action", "The bible of Groovy");
     book.PublicationDate = cal.AddSeconds(3);
     s.Save(book);
     tx.Commit();
     s.Clear();
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="s"></param>
 private void DeleteTestBooks(IFullTextSession s)
 {
     ITransaction tx = s.BeginTransaction();
     s.Delete("from System.Object");
     tx.Commit();
     s.Clear();
 }
예제 #31
0
        public void Transactional()
        {
            IFullTextSession s  = Search.CreateFullTextSession(OpenSession());
            ITransaction     tx = s.BeginTransaction();
            int loop            = 4;

            for (int i = 0; i < loop; i++)
            {
                s.Save(new Email(i + 1, "JBoss World Berlin", "Meet the guys who wrote the software"));
            }
            tx.Commit();
            s.Close();

            // check non created object does get found!!1
            s  = new FullTextSessionImpl(OpenSession());
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser("id", new StopAnalyzer());
            IList       result = s.CreateFullTextQuery(parser.Parse("Body:create")).List();

            Assert.IsEmpty(result);
            tx.Commit();
            s.Close();

            s = new FullTextSessionImpl(OpenSession());
            s.Transaction.Begin();
            using (IDbCommand cmd = s.Connection.CreateCommand())
            {
                s.Transaction.Enlist(cmd);
                cmd.CommandText = "update Email set Body='Meet the guys who write the software'";
                cmd.ExecuteNonQuery();

                cmd.CommandText = "insert into Email(Id, Title, Body, Header) values( + "
                                  + (loop + 1) + ", 'Bob Sponge', 'Meet the guys who create the software', 'nope')";
                cmd.ExecuteNonQuery();
            }

            s.Transaction.Commit();
            s.Close();

            s      = new FullTextSessionImpl(OpenSession());
            tx     = s.BeginTransaction();
            parser = new QueryParser("id", new StopAnalyzer());
            result = s.CreateFullTextQuery(parser.Parse("Body:write")).List();
            Assert.IsEmpty(result);
            result = s.CreateCriteria(typeof(Email)).List();
            for (int i = 0; i < loop / 2; i++)
            {
                s.Index(result[i]);
            }
            tx.Commit();                 //do the process

            s.Index(result[(loop / 2)]); //do the process out of tx

            tx = s.BeginTransaction();
            for (int i = loop / 2 + 1; i < loop; i++)
            {
                s.Index(result[i]);
            }
            tx.Commit(); //do the process
            s.Close();

            s  = Search.CreateFullTextSession(OpenSession());
            tx = s.BeginTransaction();

            // object never indexed
            Email email = (Email)s.Get(typeof(Email), loop + 1);

            s.Index(email);
            tx.Commit();
            s.Close();

            // check non indexed object get indexed by s.index
            s      = new FullTextSessionImpl(OpenSession());
            tx     = s.BeginTransaction();
            result = s.CreateFullTextQuery(parser.Parse("Body:create")).List();
            Assert.AreEqual(1, result.Count);
            tx.Commit();

            s.Delete("from System.Object");
            s.Flush();

            s.Close();
        }
예제 #32
0
        public void EagerCollectionLoad()
        {
            ISession     sess = this.OpenSession();
            ITransaction tx   = sess.BeginTransaction();

            Music music = new Music();

            music.Title = "Moo Goes The Cow";
            Author author = new Author();

            author.Name = "Moo Cow";
            music.Authors.Add(author);
            sess.Persist(author);

            author      = new Author();
            author.Name = "Another Moo Cow";
            music.Authors.Add(author);
            sess.Persist(author);

            author      = new Author();
            author.Name = "A Third Moo Cow";
            music.Authors.Add(author);
            sess.Persist(author);

            author      = new Author();
            author.Name = "Random Moo Cow";
            music.Authors.Add(author);
            sess.Persist(author);
            sess.Save(music);

            Music music2 = new Music();

            music2.Title = "The Cow Goes Moo";
            author       = new Author();
            author.Name  = "Moo Cow The First";
            music2.Authors.Add(author);
            sess.Persist(author);

            author      = new Author();
            author.Name = "Moo Cow The Second";
            music2.Authors.Add(author);
            sess.Persist(author);

            author      = new Author();
            author.Name = "Moo Cow The Third";
            music2.Authors.Add(author);
            sess.Persist(author);

            author      = new Author();
            author.Name = "Moo Cow The Fourth";
            music2.Authors.Add(author);
            sess.Persist(author);
            sess.Save(music2);
            tx.Commit();
            sess.Clear();

            IFullTextSession s = Search.CreateFullTextSession(sess);

            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser(Environment.LuceneVersion, "title", new KeywordAnalyzer());

            Lucene.Net.Search.Query query    = parser.Parse("title:moo");
            IFullTextQuery          hibQuery = s.CreateFullTextQuery(query, typeof(Music));
            IList result = hibQuery.List();

            Assert.AreEqual(2, result.Count, "Should have returned 2 Music");
            music = (Music)result[0];
            Assert.AreEqual(4, music.Authors.Count, "Music 1 should have 4 authors");
            music = (Music)result[1];
            Assert.AreEqual(4, music.Authors.Count, "Music 2 should have 4 authors");

            // cleanup
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
        public void LuceneObjectsProjectionWithList()
        {
            IFullTextSession s = Search.CreateFullTextSession(this.OpenSession());

            this.PrepEmployeeIndex(s);

            s.Clear();
            ITransaction tx     = s.BeginTransaction();
            QueryParser  parser = new QueryParser(NHibernate.Search.Environment.LuceneVersion, "Dept", new StandardAnalyzer(NHibernate.Search.Environment.LuceneVersion));

            Query          query    = parser.Parse("Dept:Accounting");
            IFullTextQuery hibQuery = s.CreateFullTextQuery(query, typeof(Employee));

            hibQuery.SetProjection(
                "Id",
                "Lastname",
                "Dept",
                ProjectionConstants.THIS,
                ProjectionConstants.SCORE,
                ProjectionConstants.BOOST,
                ProjectionConstants.DOCUMENT,
                ProjectionConstants.ID,
                ProjectionConstants.DOCUMENT_ID);

            IList result = hibQuery.List();

            Assert.IsNotNull(result);

            object[] projection = (Object[])result[0];
            Assert.IsNotNull(projection);
            Assert.AreEqual(1001, projection[0], "id incorrect");
            Assert.AreEqual("Jackson", projection[1], "last name incorrect");
            Assert.AreEqual("Accounting", projection[2], "dept incorrect");
            Assert.AreEqual("Jackson", ((Employee)projection[3]).Lastname, "THIS incorrect");
            Assert.AreEqual(projection[3], s.Get <Employee>(projection[0]), "THIS incorrect");
            //Assert.AreEqual(1.0F, projection[4], "SCORE incorrect");
            Assert.AreEqual(1.0F, projection[5], "BOOST incorrect");
            Assert.IsTrue(projection[6] is Document, "DOCUMENT incorrect");
            Assert.AreEqual(4, ((Document)projection[6]).GetFields().Count, "DOCUMENT size incorrect");
            Assert.AreEqual(1001, projection[7], "ID incorrect");
            Assert.IsNotNull(projection[8], "Lucene internal doc id");

            // Change the projection order and null one
            hibQuery.SetProjection(
                ProjectionConstants.DOCUMENT,
                ProjectionConstants.THIS,
                ProjectionConstants.SCORE,
                null,
                ProjectionConstants.ID,
                "Id",
                "Lastname",
                "Dept",
                ProjectionConstants.DOCUMENT_ID);

            result = hibQuery.List();
            Assert.IsNotNull(result);

            projection = (object[])result[0];
            Assert.IsNotNull(projection);

            Assert.IsTrue(projection[0] is Document, "DOCUMENT incorrect");
            Assert.AreEqual(4, ((Document)projection[0]).GetFields().Count, "DOCUMENT size incorrect");
            Assert.AreEqual(projection[1], s.Get <Employee>(projection[4]), "THIS incorrect");
            //Assert.AreEqual(1.0F, projection[2], "SCORE incorrect");
            Assert.IsNull(projection[3], "BOOST not removed");
            Assert.AreEqual(1001, projection[4], "ID incorrect");
            Assert.AreEqual(1001, projection[5], "id incorrect");
            Assert.AreEqual("Jackson", projection[6], "last name incorrect");
            Assert.AreEqual("Accounting", projection[7], "dept incorrect");
            Assert.IsNotNull(projection[8], "Lucene internal doc id");

            // cleanup
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }