In Grails, I have two domain classes having many to many relationship
class VisitingUser
{
String name
static hasMany = [visitedCountries:VisitedCountry]
static belongsTo = VisitedCountry
}
class VisitedCountry
{
String countryName
static hasmany=[users:VisitingUser]
}
I want all those users who visited country "india" AND "usa" both.
Currently I am solving this problem by getting two list of visitingUsers, one for "india" and other for "usa" and then putting them in a Set.
I want a solution with using createCriteria or dynamic finder.
I don't think this is possible with a criteria query, and it's definitely not possible with a dynamic finder. Here's a solution with HQL though:
VisitingUser.executeQuery('''
select distinct u from VisitingUser u where
u in (
select u from VisitingUser u join u.visitedCountries country where country.countryName = 'usa'
)
and u in (
select u from VisitingUser u join u.visitedCountries country where country.countryName = 'india'
)
''')
Two unrelated things - VisitedCountries
should be called VisitedCountry
(although the set name visitedCountries
makes sense because it will potentially have multiple elements), and the relationship should be many-to-many.
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.