Restrict the scope of data when using withCriteria

后端 未结 1 1736
借酒劲吻你
借酒劲吻你 2021-01-24 22:52

I currently have the following 3 domain classes :

User.groovy

class User {
    ...

    static hasMany = [
        ...
        ]

    static belongsTo =         


        
相关标签:
1条回答
  • 2021-01-24 23:22

    Register your desired JSON Object marshaller for Course in bootstrap as below:

    //Bootstrap
    def init = { servletContext ->
        JSON.registerObjectMarshaller(Course){
            def returnObj = [:]
            returnObj.id = it.id
            returnObj.title = it.title
    
            returnObj
        }
    }
    

    The above registers to only return the fields of Course when converted and rendered to JSON. Note this is going to permanently marshal Course to only return its fields and not its associations. If needed temporarily then you can very well follow Tim's approach.

    In case you want to make it generic for the all the fields, then:

    JSON.registerObjectMarshaller(Course){course ->
        def fields = grailsApplication.domainClasses
                                      .find{it.name == 'Course'}
                                      .properties
                                      .findAll{!it.association}
                                      .name - 'version' //Remove version if req.
    
        return fields.collectEntries{[it, course."$it"]}
    }
    

    provided grailsApplication is injected to Bootstrap.groovy

    To add, if the intention is not to modify the way JSON is built but to reconcile the criteria result then use projections to get the required property:

    def courses = Course.withCriteria {      
       universities {
         eq('id', Long.parseLong(params.universityId))
       }
       projections{
          property('id')
          property('title')
       }
    }
    

    UPDATE:
    In order to retrieve results as mapped entities then I would follow HQL as shown here or use createCriteria and transform the result to map as below (untested):

    import org.hibernate.transform.Transformers
    
    def criteria = Course.createCriteria()
    criteria.resultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
    def courses = criteria.list {      
       universities {
         eq('id', Long.parseLong(params.universityId))
       }
       projections{
          property('id')
          property('title')
       }
    }
    

    I am not sure aliases will be created by the property names. I you face any issue, you can swiftly fallback to HQL query.

    0 讨论(0)
提交回复
热议问题