0

我需要查询具有两个关联对象的域。

class UserVideo {
    User user
    Video video
}
class User {
    String name
}
class Video {
    String title
}

我需要找到属于给定用户的所有 UserVideos 并且 video.title 就像一个字符串。例如“查找属于用户‘Fred’的所有 UserVideo,并且 Video.title 类似于‘%Potter%’。” 无论我尝试过什么,都没有任何效果。

根据要求,这是我的操作代码:

    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()]
}

这是我得到的错误:

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]
4

2 回答 2

2

像这样的东西

def c = UserVideo.createCriteria()
def results = c.list {
  eq("user", User.findByName("Fred"))
  video {
    ilike("title", "%Potter%")
  }
}

更新 - 尝试 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}%"])
于 2013-04-28T02:00:54.813 回答
1

您可以executeQuery在域类上使用。

样本:

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}"
于 2013-04-28T02:00:40.880 回答