【问题标题】:Grails 3 profiles,JSON rendering and One to Many with selfGrails 3 配置文件、JSON 渲染和一对多与自我
【发布时间】:2017-06-02 13:19:16
【问题描述】:

我正在使用 gson 和网络配置文件。

我的域是:

package json
import grails.rest.*

@Resource(readOnly = false, formats = ['json', 'xml'])
class Hero {
    String name
    String data
    String relation
    Book book
    static hasMany = [children: Hero]

我的控制器是:

package json

import grails.rest.*
import grails.converters.*

class HeroController extends RestfulController {
    static responseFormats = ['json', 'xml']
    HeroController() {
        super(Hero)
    }
    def show(Hero hero){
        respond hero
    }
}

我的儿子:

hero.gson

import json.Hero

model {
    Hero hero
}

json tmpl.hero(hero)

_hero.gson

import json.Hero

model {
    Hero hero
}

json {
    //data hero.data
    id hero.id
    data(relation: hero.relation)
    name hero.name
    children g.render(hero.children)
}

如果我使用 restful 配置文件运行它,那么所有子节点都会正确呈现。 如果我使用网络配置文件,则只会呈现两层深度。

我的预期结果是:

{
    "id": 4,
    "data": {
        "relation": "e"
    },
    "name": "e",
    "children": [{
            "id": 2,
            "data": {
                "relation": "c"
            },
            "name": "c",
            "children": [{
                    "id": 1,
                    "data": {
                        "relation": "b"
                    },
                    "name": "b",
                    "children": []
                }
            ]
        }

是否可以进行一对多的 json 渲染(与 restful 配置文件一样)? 有没有办法控制渲染的深度?

附:我阅读了文档,这部分对我来说不是很清楚:

如果您希望将作者作为渲染的一部分, 有两个要求,首先你必须确保关联 已初始化。

如果render方法遇到代理,就不会遍历到 关系以避免 N+1 查询性能问题。相同 适用于一对多集合关联。如果协会有 未初始化的渲染方法将不会遍历 收藏!

因此,您必须确保您的查询使用连接:

Book.findByTitle("The Stand", [fetch:[author:"join"]])

其次,在调用渲染方法时,你应该通过 deep 论据:

json g.render(book, [deep:true])

【问题讨论】:

    标签: json grails one-to-many profile


    【解决方案1】:

    是的,可以使用网络配置文件呈现您的 json。 我可以通过添加到 build.gradle 来做到这一点:

    apply plugin:"org.grails.plugins.views-json"
    
    dependencies {
    
        compile "org.grails.plugins:views-json"
        compile "org.grails.plugins:views-json-templates"
    
    
    
    bootRun {
        jvmArgs('-Dspring.output.ansi.enabled=always')
        addResources = true
    }
    

    并使用您的代码在域类中稍作更改: 孩子懒惰:假

    @Resource(readOnly = false, formats = ['json', 'xml'])
    class Hero {
        String name
        String data
        String relation
        //Book book
        static hasMany = [children: Hero]
    
        static mapping = {
            children lazy: false
        }
    

    这将改变获取模式。 你可以在这里咨询获取:

    enter link description herehttp://docs.grails.org/3.1.1/ref/Database%20Mapping/fetch.html

    http://docs.grails.org/3.1.1/guide/single.html#fetching

    【讨论】:

    • 看来我已经添加了旧版本:classpath "org.grails.plugins:views-gradle:1.1.*...
    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2017-06-05
    • 2011-05-17
    • 1970-01-01
    • 2012-03-27
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多