【问题标题】:Grails - findAll Posts Created Today by UserGrails - 查找用户今天创建的所有帖子
【发布时间】:2011-09-21 07:31:59
【问题描述】:

我有一个域对象。

class Post {
  User user
  String subject
  String body
  Date dateCreated
}

我该怎么做?直接 GORM、HQL 或标准是更好的方法吗? 我不知道什么样的日期操作(“today eq”)会在标准中起作用。

【问题讨论】:

    标签: hibernate grails date grails-orm


    【解决方案1】:

    我可能会做一个命名查询

    class Post {
      User user
      String subject
      String body
      Date dateCreated
    
         static namedQueries = {
           todaysPosts {
              def now = new Date().clearTime()
              between('dateCreated', now, now+1)
           }
       }
    }
    

    然后你可以像这样使用它:

    Post.todaysPosts.count()
    

    Post.todaysPosts.list()
    Post.todaysPosts.list(max: 10, offset: 5)
    

    你甚至可以做

    Post.todaysPosts.findAllByUser(user)
    

    Here 更多关于命名查询

    【讨论】:

    • 虽然看起来很不错,但在 Grails 4.x 中已弃用 namedQueries。改用 where 查询。
    • 同意。这在 2011 年得到了回答,当时有效。
    【解决方案2】:

    这是一个标准示例:

    // assuming future posts are disallowed
    def posts = Post.withCriteria {
        eq('user', user)
        ge('dateCreated', new Date().clearTime())
    }
    
    // if you must accommodate future posts
    def today = new Date().clearTime()
    def posts = Post.withCriteria {
        eq('user', user)
        ge('dateCreated', today)
        lt('dateCreated', today.plus(1))
    }
    

    【讨论】:

    • 如果today <= dateCreated < today + 1... 不包括所有日期?
    【解决方案3】:

    我会使用 Grails 动态查找器来完成此任务:

    Post.findAllByUserAndDateCreatedGreaterThanEquals(currentUser, new Date().clearTime())
    

    其中“currentUser”是当前用户的一个实例

    【讨论】:

    • 忘记了“AndUserEquals”,因为他们只想要当前用户的东西。
    【解决方案4】:
    String sqlQuery = "SELECT * FROM Post p WHERE p.dateCreated  = NOW()"
    def e = Post.executeQuery(sqlQuery)
    

    【讨论】:

    • 这是特定于数据库的,不是吗? NOW(),或 SYSDATE,或他们正在使用的数据库的任何内容。
    • 这当然是一个解决方案,但它不使用Hibernate或GORM。
    【解决方案5】:

    为了完整起见,这是一个用 HQL 编写的查询:

    def yourUser = User.get(1)
    def results = Post.executeQuery( "select * from Post a where a.user = :user and a.dateCreated >= :dateCreated", [user : yourUser , dateCreated : new Date().clearTime()] );
    

    @Tyndall:这个问题有很多答案,只要选择一个你觉得舒服的。

    【讨论】:

    • @sbglasius:视情况而定。您始终可以将查询字符串格式化为多行以使其更易于阅读
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2011-12-20
    相关资源
    最近更新 更多