Skip to content

Instantly share code, notes, and snippets.

@joeRinehart
Created August 18, 2012 15:42
Show Gist options
  • Save joeRinehart/3387801 to your computer and use it in GitHub Desktop.
Save joeRinehart/3387801 to your computer and use it in GitHub Desktop.
GrailsModelsPart2_2
package recordstore
class Album {
// Mappings
static hasMany = [
songs : Song
]
// Properties
String name
List songs // ordered collection of songs
static constraints = {
}
}
package blog
class BlogCategory {
static hasMany = [
entries : BlogEntries
]
static mapping = {
entries: sort:'dateCreated', order:'desc'
}
}
mysql> select * from song;
+----+---------+----------+-------------+-----------+
| id | version | album_id | name | songs_idx |
+----+---------+----------+-------------+-----------+
| 1 | 0 | 1 | Shame | 0 |
| 2 | 0 | 1 | Die Die Die | 1 |
+----+---------+----------+-------------+-----------+
2 rows in set (0.00 sec)
@Test
void songsWithinAnAlbumAreOrdered() {
def originalSongCount = Song.list().size()
// Create and save an album
def album = new Album( name: "Emotionalism" )
def song = new Song( name: "Shame" )
def song2 = new Song( name: "Die Die Die" )
album.addToSongs( song )
album.addToSongs( song2 )
// Lists have an innate and reliable order
def tmp = album.songs.get( 0 )
album.songs[0] = album.songs[1]
album.songs[1] = tmp
assert album.songs[0] == song2
assert album.songs[1] == song
}
@Test
void weCanQueryForSongsViaFindersOrHQL() {
// Create and save an album
def album = new Album( name: "Emotionalism" )
def song = new Song( name: "Die Die Die" )
def song2 = new Song( name: "Shame" )
album.addToSongs( song )
album.addToSongs( song2 )
album.save()
// Dynamic finder
assert Song.findAllByAlbum( album ).size() == 2
// HQL
assert Song.executeQuery( "from Song s where s.album = ?", [ album ] ).size() == 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment