Over a million developers have joined DZone.

Grails Goodness: Getting First or Last Instance of Domain Classes

· Java Zone

Learn more about how the Java language, tools and frameworks have been the foundation of countless enterprise systems, brought to you in partnership with Salesforce.

Since Grails 2 we can get the first or last instance of a domain class with the first() and last() method on domain classes. We can optionally use an argument to set the column name to sort by. If we don't specify a column name the id column is used.

import com.mrhaki.grails.Course

createCourse 'Grails University Getting Started', Date.parse('yyyy-MM-dd', '2013-11-01')
createCourse 'Grails University RESTful Applications'
createCourse 'Spock Sessions', Date.parse('yyyy-MM-dd', '2013-09-01')

void createCourse(final String name, final Date start = null) {
    new Course(name: name, start: start).save()

assert Course.first().name == 'Grails University Getting Started'
assert Course.first().start.format('yyyy-MM-dd') == '2013-11-01'

assert Course.last().name == 'Spock Sessions'
assert Course.last('name').name == 'Spock Sessions'

assert Course.last('start').name == 'Grails University Getting Started'
assert Course.first(sort: 'start').start == null

Discover how the Force.com Web Services Connector (WSC) is a code-generation tool and runtime library for use with Force.com Web services, brought to you in partnership with Salesforce.


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}