How to access a user defined Grails Project Package Name using the domain class string name

雨燕双飞 提交于 2019-12-25 07:35:46

问题


What we are attempting to do is create one grails application with multiple package names. Each package name will represent a different business entity and functionality.

Essentially multiple grails applications in one grails application project with each application being represented by having it's own package.

We will then like to uniquely prefix the tables based on the package name without having to prefix the domain class names or use static mapping on every domain class. The DefaultNamingStrategy works well with handling table prefixing on every domain class in the project.

The issue I am having is accessing the project Package name for each domain class name string that is called in the classToTableName method. For each domain class string that is passed to the classToTableName method, I need the user defined project Package name to differentiate what unique prefix should be assigned on the table based on the package name.

I have tried several different things in order to access the project package name using getArtefacts, or GroovyClassLoader, but the output is java.lang or the grails.commons package.

Any assistance that can be provide would be much appreciated. The CustomNamingStrategy class below has been created in the groovy folder of the project and is referenced in the hibernate section of the DataSource.groovy file.

class CustomNamingStrategy extends DefaultNamingStrategy {
    String classToTableName( String className ) {
        def packageName
        def prefix = ""

        // How do I access the package name of the domain class using className string?

        if (packageName == 'recordretention'){
            prefix = "Rr"
        }
        className = prefix + className

        covertFromCamelCase(super.classToTableName(className))
    }

    String covertFromCamelCase(String input) {
        GrailsNameUtils.getNaturalName(input).replaceAll("\\s", "_").toUpperCase();
    }
}

回答1:


After a lot of searching, it is the Holders class in grails 2.x that provides the access needed for classes in the src/groovy folder.

Class clazz = Holders.grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz

packageName = clazz.getPackage().getName()



回答2:


Untested but assuming that your class names between 'sub-applications' are different, you might be able to use grailsapplication lookup methods(untested getartefactbylogicalpropertyname) http://grails.org/doc/latest/api/org/codehaus/groovy/grails/commons/GrailsApplication.html#getArtefactByLogicalPropertyName(java.lang.String,%20java.lang.String)

You could lookup grailsapplication via applicationholder.



来源:https://stackoverflow.com/questions/17051566/how-to-access-a-user-defined-grails-project-package-name-using-the-domain-class

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