Grails createCriteria on abstract domain

痴心易碎 提交于 2019-12-11 11:45:12

问题


I am quite curious how one would use the criteria builder to access fields of an inherited class.

Let's assume we have the following class:

class A { 
  String fieldOne 
  String fieldTwo

  static hasMany = [childs: AbstractChildClass]

}

and the abstract child class would look like this:

abstract class AbstractChildClass {

  Integer valueOne
  Integer valueTwo
  A a

  static mapping
      tablePerHierarchy false
  }
}

of course there are several extending classes such as:

class ExtendingClassOne extends AbstractChildClass {

    DesiredObject desiredObject

    static mapping = {
        tablePerHierarchy false
    }

}

let's also assume there is the class DesiredObject which looks like this:

class DesiredObject {
    String infoA
    String infoB
}

The question is how one would get the fields infoA and infoB by creating a criteria for class A. My approach so far is this:

A.createCriteria().list {
    childs {
        desiredObject {
            ilike('infoA', '%something%')
        }
    }
}

This of course does not work because in the table ExtendingClassOne is only the id of the desiredObject and I have no clue how to join the object with the criteria builder to get its fields.

Thank you for reading.

Marco


回答1:


don't expect 100% match between your domain model and the DB schema it's related to.

In your case the polymorphism would work only with tablePerHierarchy true for AbstractChildClass.

If you do want to stick with tablePerHierarchy false, you can define your class like:

class A { 

  static hasMany = [ childrenOne:ExtendingClassOne, childrenTwo:ExtendingClassTwo ]

}

thus your query would be as simple as:

A.withCriteria{
  for( String c in [ 'childrenOne', 'childrenTwo' ] ){
    "$c"{
      desiredObject {
        ilike('infoA', '%something%')
      }
    }
  }
}


来源:https://stackoverflow.com/questions/25544648/grails-createcriteria-on-abstract-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!