2016-09-23 45 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"}]