I have a domain object.
class Post {
User user
String subject
String body
Date dateCreated
}
How do I go about this? Is straight GORM, HQL, or criteria the better way? I didn't know what kind of date manipulation ("today eq") would work in criteria.
I would probably make a named query
class Post {
User user
String subject
String body
Date dateCreated
static namedQueries = {
todaysPosts {
def now = new Date().clearTime()
between('dateCreated', now, now+1)
}
}
}
Then you can use it like:
Post.todaysPosts.count()
or
Post.todaysPosts.list()
Post.todaysPosts.list(max: 10, offset: 5)
you can even do
Post.todaysPosts.findAllByUser(user)
Here is more on named queries
Here's a criteria example:
// 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))
}
I would use Grails Dynamic Finders to accomplish this:
Post.findAllByUserAndDateCreatedGreaterThanEquals(currentUser, new Date().clearTime())
Where "currentUser" is an instance of the current user
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With