gpt4 book ai didi

json - 在评估子项及其属性的父项上执行createCriteria()

转载 作者:行者123 更新时间:2023-12-02 14:29:59 26 4
gpt4 key购买 nike

我在Grails中使用的Hibernate具有正确设置的Parent域类和Child域类,已完全配置,具有静态hasManybelongsTo属性。尽管在实用性方面,它也可以应用于其他方案,但我们只为该方案使用类名ParentChild

为了测试此映射,我还执行了许多成功的CRUD。尽管过了一会儿,仍会出现预先查询。我目前只能执行一些“高级”查询,下面对它们进行了总结。使用给定的Domain映射:

class Parent {
Long id
static hasMany = [ children: Child ]
}

class Child {
Long id
static belongsTo = [ parent: Parent ]
}

如何选择以下条件:
  • 选择所有没有 child 的 parent
  • 选择带有 child 的所有父项
  • 选择所有有男 child 的 parent (因此,当通过as JSON groovy类型转换为JSON转换为JSON时,仅应包括男 child )

  • 我不知道如何开始编码1和2,也许与 child.size()有关-我真的不知道。尽管我在3中的想法是:
    ArrayList<Parent> PARENTS_WITH_SON = Parent.createCriteria().list {
    children {
    eq("gender", "male")
    }
    }

    但是问题在于,当转换为JSON时,它会包含非男性条目。有人可以帮我解决问题吗?使用 createCriteria()会很好,但也可以在 HQL中使用。

    最佳答案

    1和2真的很简单:

    1.选择所有没有 child 的 parent

    Parent.createCriteria().list {
    sizeEq("children", 0)
    }

    2.选择所有带 child 的 parent
    Parent.createCriteria().list {
    sizeGt("children", 0)
    }

    3.选择所有带男孩的 parent (因此,当通过as JSON groovy类型转换转换为JSON时,应该只包括男孩)
    Parent.createCriteria().listDistinct {
    children {
    eq("gender", "male")
    }
    }

    使用上面的查询,您将获得 parent 中有男婴的集合。但是,当您执行直接JSON转换时,GORM将获取 parent 的所有 child 。因此,您可以编写自定义JSON转换器,也可以修改查询以仅返回Map中所需的数据。
    /*
    create a new Grails Criteria that internally will use
    Hibernate's org.hibernate.Criteria.
    */
    List<Map<String, Object>> resultList = Parent.createCriteria().list {
    /*
    Set a strategy for handling the query results.
    This determines the "shape" of the query result.

    See org.hibernate.Criteria.setResultTransformer(...)

    CriteriaSpecification.ALIAS_TO_ENTITY_MAP transformer will transform the results into a Map<String, Object>
    */
    resultTransformer(org.hibernate.criterion.CriteriaSpecification.ALIAS_TO_ENTITY_MAP)

    /*
    Join an association using the specified join-type,
    assigning an alias to the joined association.

    org.hibernate.Criteria.createAlias(...)
    */
    createAlias("children", "child", JoinType.INNER_JOIN);

    projections {
    property("id", "parentId")
    property("child.id", "childId")
    property("child.gender", "gender")
    }

    eq("child.gender", "MALE")
    }

    这将为您提供一个以parentId,childId和gender为键的 map 列表。杰森为此:
    [
    {
    "childId": 1,
    "gender": "MALE",
    "parentId": 2
    },
    {
    "childId": 3,
    "gender": "MALE",
    "parentId": 2
    },
    {
    "childId": 4,
    "gender": "MALE",
    "parentId": 3
    },
    {
    "childId": 5,
    "gender": "MALE",
    "parentId": 3
    }
    ]

    关于json - 在评估子项及其属性的父项上执行createCriteria(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37545365/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com