Java Reference
In-Depth Information
Listing 9.2. The DAO interface with the CRUD methods for Person
import java.util.List;
public interface PersonDAO {
List<Person> findAll();
Person findById(long id);
List<Person> findByLastName(String name);
Person create(Person p);
Person update(Person p);
boolean delete(long id);
}
The implementation of the DAO is done in Groovy using the groovy.sql.Sql class,
just as in chapter 8 on databases. The only part that differs from that chapter is that the id
attribute is generated by the database. Here's how to use the Sql class to retrieve the gen-
erated ID:
Person create(Person p) {
String txt = 'insert into people(id, first, last) values(?, ?, ?)'
def keys = sql.executeInsert txt, [null, p.first, p.last]
p.id = keys[0][0]
return p
}
The executeInsert method returns the collection of generated values, and in this case
the new ID is found as the first element of the first row.
The Spock test for the DAO is similar to those shown in chapter 6 on testing or chapter
8 on databases. The only new part is that the when / then block in Spock is repeated to
insert and then delete a new Person . When Spock sees a repeat of the when / then pair,
it executes them sequentially. Listing 9.3 shows this test, which inserts a row representing
Peter Quincy Taggart, [ 11 ] verifies that he's stored properly, and then deletes the row. Recall
that the seriously cool old method in Spock evaluates its argument before executing the
when block, so it can be compared to the rest of the expression evaluated after the when
block is done.
11 Remember him? Commander of the NSEA Protector? “Never give up, never surrender?” That's Galaxy Quest , a
Star Trek parody,but arguably one ofthe better Star Trek movies. Did youknowthat the designation ofthe Protector
was NTE-3120, and that NTE stood for “Not The Enterprise”? By Grabthar's hammer, that's the kind of research
you are obligated to do when you write a Groovy/Java integration book.
 
Search WWH ::




Custom Search