Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Existing Groovy DSLs


[ 226 ]

GORM has automatically created a customer table for us in the devDB database. The
table has two fields by default, for the row id and the object version. The two fields
we added to Customer have been mapped to the first_name and last_name fields
of type varchar(255) columns in the database.


Using domain classes

If the Customer class was a normal POGO class, this will only allow us to construct
it and interact with its properties at this point. However, Grails has added some
persistence methods to the Customer class. We won't build a full-blown Grails app
with controllers and views in this chapter, but we have several options for exercising
our GORM objects without that. The first is to use Groovy Console. To do so, we
need to launch it indirectly via the grails command:


$grails console


This will launch the groovyConsole app we've used before with the GORM objects
fully ready to use. I recommend this as a great way to explore your GORM objects
and see how they work. In keeping with the rest of the book, we will illustrate how
the GORM persistence methods work with a Spock test. We will want a Spock
integration test that actually uses GORM persistence rather that a unit test that uses
mocks. We can create a template integration test for the Customer class from the
grails command line:


$grails create-integration-test Customer


Next, we edit this to add some interactions with the GORM persistence model
for Customer:


@Integration
@Rollback
class CustomerSpec extends Specification {
void "Gorm has added methods for persistence"() {
given: "We save a domain object with save"
def barney = new Customer(firstName: "Barney",
lastName: "Rubble")
barney.save()

when: "we get it from the database"
def fred = Customer.get(1)

then:
fred.firstName == "Barney"

http://www.ebook3000.com
Free download pdf