开发者

NHibernate - flush before querying?

开发者 https://www.devze.com 2022-12-17 21:49 出处:网络
I have a repository class that uses an NHibernate session to persist objects to the database. By default, the repository doesn\'t use an explicit transaction - that\'s up to the caller to manage. I ha

I have a repository class that uses an NHibernate session to persist objects to the database. By default, the repository doesn't use an explicit transaction - that's up to the caller to manage. I have the following unit test to test my NHibernate plumbing:

[Test]开发者_StackOverflow社区
public void NHibernate_BaseRepositoryProvidesRequiredMethods()
{            
    using (var unitOfWork = UnitOfWork.Create())
    {
        // test the add method
        TestRepo.Add(new TestObject() { Id = 1, Name = "Testerson" });
        TestRepo.Add(new TestObject() { Id = 2, Name = "Testerson2" });
        TestRepo.Add(new TestObject() { Id = 3, Name = "Testerson3" });

        // test the getall method
        var objects = TestRepo.GetAll();
        Assert.AreEqual(3, objects.Length);

        // test the remove method
        TestRepo.Remove(objects[1]);
        objects = TestRepo.GetAll();
        Assert.AreEqual(2, objects.Length);

        // test the get method
        var obj = TestRepo.Get(objects[1].Id);
        Assert.AreSame(objects[1], obj);
    }
}

The problem is that the line

Assert.AreEqual(3, objects.Length);

fails the test because the object list returned from the GetAll method is empty. If I manually flush the session right after inserting the three objects, that part of the test passes. I'm using the default FlushMode on the session, and according to the documentation, it's supposed to flush before running the query to retrieve all the objects, but it's obviously not. What I am missing?

Edit: I'm using Sqlite for the unit test scenario, if that makes any difference.


You state that

according to the documentation, it's supposed to flush before running the query to retrieve all the objects

But the doc at https://www.hibernate.org/hib_docs/v3/api/org/hibernate/FlushMode.html, the doc states that in AUTO flush mode (emphasis is mine):

The Session is sometimes flushed before query execution in order to ensure that queries never return stale state. This is the default flush mode.

So yes, you need to do a flush to save those values before expecting them to show up in your select.

0

精彩评论

暂无评论...
验证码 换一张
取 消