简体   繁体   中英

Querying a list of items from a one-to-many relationship in Grails

If I have a class called Artist, which has many Song:

class Artist {
    String name
    static hasMany = [songs : Song]
}

class Song {
    String title
    Integer duration
}

I want to know which artists sang a list of titles. For example I want to know the artists who sang Hello , My Love , and Yesterday (An array of String). What is the best way to do this?

I tried using criteria and findAll, but can't really figure out which is the best way. Any ideas?

This HQL will work:

def artists = Artist.executeQuery(
   'select distinct a from Artist a join a.songs song where song.title in (:titles)',
   [titles: ['Hello', 'My Love', 'Yesterday']])

It will return a list of artists, but if there's only one result you can get it as artists[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM