Reputation: 1468
I need to query on a domain that has two associated objects.
class UserVideo {
User user
Video video
}
class User {
String name
}
class Video {
String title
}
I need to find all the UserVideos that belong to a given user and where the video.title is like a string. For example "Find all the UserVideos that belong to user 'Fred' and the Video.title is like '%Potter%'." No matter what I've tried, nothing works.
As requested, here is the code I have for my action:
def list(Integer max, String title) {
def userName = springSecurityService?.principal?.username
def user = User.findByUsername(userName)
params.max = Math.min(max ?: 10, 100)
def results
if (title) {
def c = UserVideo.createCriteria()
results = c.list {
eq("user", user)
video {
ilike("title", "%${title}%")
}
}
} else {
results = UserVideo.findAllByUser(user, params)
}
def userVideos = results.collect({ UserVideo uv ->
[uId: uv.user?.id, vId: uv.video?.id, number: uv.number, title: uv.video?.title,
format: uv.video?.format?.name, rating: uv.video?.rating?.name, genres: uv.video?.genreNames]
})
[userVideos: userVideos, total: UserVideo.count()]
}
Here is the error I get:
URI
/movies/userVideo/list
Class
org.h2.jdbc.JdbcSQLException
Message
Column "VIDEO_ALIA1_.TITLE" not found; SQL statement: select this_.user_id as user1_2_0_, this_.video_id as video2_2_0_, this_.number as number2_0_ from user_video this_ where this_.user_id=? and (lower(video_alia1_.title) like ?) [42122-170]
Upvotes: 0
Views: 736
Reputation: 50275
You can use executeQuery
on domain class.
Sample:
def newUser = new User(name: "Fred")
def video = new Video(title: "Harry Potter")
[newUser, video]*.save(flush: true)
def userVideo = new UserVideo(user: newUser, video: video)
userVideo.save(flush: true)
def result = UserVideo.executeQuery(
"Select distinct uv from UserVideo uv " +
"where uv.user.name = :userName " +
"and uv.video.title like :title",
[userName : "Fred", title: "%Potter%"],
[max: 10, offset: 10]) //EDIT
//Pagination included. (max: 10, offset: 10) can also be part of the params maps like
//[userName : "Fred", title: "%Potter%", max: 10, offset: 10]
assert "Fred has the movie Harry Potter" ==
"${result[0].user.name} has the movie ${result[0].video.title}"
Upvotes: 1
Reputation: 12238
Something like this
def c = UserVideo.createCriteria()
def results = c.list {
eq("user", User.findByName("Fred"))
video {
ilike("title", "%Potter%")
}
}
Update - Try HQL
UserVideo.executeQuery("""
Select uv
From UserVideo as uv join uv.video v join uv.user u
where lower(v.title) like lower(:title)
and u = :user
""", [user: user, title: "%${title}%"])
Upvotes: 2