Brian's Waste of Time

Thu, 16 Mar 2006

jDBI 2.0 Accidental Feature

I got an accidental feature in the upcoming 2.0 jDBI when I implemented forward-only external iteration (via an iterate() method on Query:

    public void testIteratorBehavior2() throws Exception
    {
        h.insert("insert into something (id, name) values (1, 'keith')");
        h.insert("insert into something (id, name) values (2, 'eric')");

        ResultIterator<Something> i = h.createQuery("select * from something order by id")
                .map(Something.class)
                .iterator();

        Something first = i.next();
        assertEquals("keith", first.getName());
        Something second = i.next();
        assertEquals(2, second.getId());
        assertFalse(i.hasNext());

        i.close();
    }

I realized that providing the iterate method provided all that was needed for Iterable, so we also get...

    public void testIterable() throws Exception
    {
        int count = 0;
        h.insert("insert into something (id, name) values (1, 'keith')");
        h.insert("insert into something (id, name) values (2, 'keith')");

        for (Something s : h.createQuery("select * from something").map(Something.class))
        {
            assertEquals("keith", s.getName());
            count++;
        }
        assertEquals(2, count);
    }

Nifty! Looking forward to getting this release out =)

writebacks...

Brian McCallister

close()
Note that the second form can be made to not leak resources by closing stuff after a hasNext() returns false. This seems kind of dangerous though in the case where someone wants to delete the last item via remove(). Will think on it. Nice to get the automagic close, but dont want to bite anyone.

comment...

 
Name:
URL/Email: [http://... or mailto:you@wherever] (optional)
Title: (optional)
Spam Guard, translate l33t to English: (hint, it's an Australian animal, plural form)
Comments:
Save my Name and URL/Email for next time