Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Grails Goodness: Getting First or Last Instance of Domain Classes

DZone's Guide to

Grails Goodness: Getting First or Last Instance of Domain Classes

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

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

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}