Grails - findAll Posts created by the user today

I have a domain object.

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

How can I do it? Is direct GORM, HQL or better? I did not know which date manipulations ("today eq") would work in the criteria.

+4
source share
5 answers

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's more for named queries

+7
source

Here is an example of criteria:

 // 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)) } 
+4
source

I would use Grails Dynamic Finders to accomplish this:

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

Where "currentUser" is the current user instance

+3
source
 String sqlQuery = "SELECT * FROM Post p WHERE p.dateCreated = NOW()" def e = Post.executeQuery(sqlQuery) 
0
source

For completeness, this is a query written in 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: there are many answers to this question, just take the one that is comfortable with you.

0
source

All Articles