2016-09-23 98 views
2

我在想如何列出Grails域并同时排除某些字段。我猜测解决方案一定很简单,但我看不到它。如何在列出Grails域时排除某些字段?

我准备了一些例如与域用户:

class User implements Serializable { 
    String username 
    String email 
    Date lastUpdated 
    String password 
    Integer status 

    static constraints = { } 

    static mapping = { } 
} 

在这一点上,我想列出具有低于2

render User.findAllByStatusLessThen(2) as JSON 

我想渲染JSON应答,而不向客户方状态的所有用户一些领域。例如,我只想渲染领域用户名LASTUPDATED所以呈现JSON看起来像这样的用户:

[{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}] 

什么是实现这一目标的最简单的方法?

回答

3

Yeah.It的simple.Try下面的解决方案

  1. 溶液1

    List userList = User.where{ status < 2 }.property("username").property("lastUpdated").list() 
    
    render userList as JSON 
    

output

[{"user1", "2016-09-21 06:49:46"}, {"user2", "2016-09-22 11:24:42"}] 
  • 所以lution 2 - 使用此,您将在Key-Value对获取输出

    List userList = User.findAllByStatusLessThen(2)?.collect{ 
        [username : it.username, lastUpdated: it.lastUpdated]} 
    
    render userList as JSON 
    
  • output

    [{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}] 
    
    +0

    感谢您的优势你的意见。解决方案2适合我的情况。 – matox

    2

    您正在寻找Grails的projections

    def result = Person.createCriteria().list { 
        lt("status", 2) 
        projections { 
         property('username') 
         property('lastUpdated') 
        } 
    } as JSON 
    
    1

    那么如果你想要得到的结果是在key-value对你可以采取HQL查询

    def query = """select new map(u.username as username, u.lastUpdated as lastUpdated) from User u where status < 2""" 
    def result = User.executeQuery(query) 
    println (result as JSON) 
    

    这会给你的输出如下

    [{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}]