gpt4 book ai didi

grails - 在Grails中,如何获得对特定类使用的数据源的引用?

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

在我正在研究的项目中(在Grails 2.5.4 / Hibernate 4.3中),我有很多不同的类,使用了一些不同的dataSources。我需要确定两个给定的Class对象是否使用相同的dataSource。我想做的是这样的:

Boolean doDataSourcesMatch(Class a, Class b)
{
return a.mapping.datasource == b.mapping.datasource
}

但是当然不行,因为 a.mapping是一个闭包。有谁知道如何访问类使用的数据源?我不需要知道连接的任何属性,只需知道两个类的查询是否将使用相同的连接即可。

非常感谢!

最佳答案

尽管这些都没有具体说明,但它们可能会有所帮助:

  • http://grails.1312388.n4.nabble.com/How-can-I-get-the-column-name-that-a-property-maps-to-for-a-domain-class-td4633766.html
  • How to get the name of the table GORM object is mapped to?

  • 我还没有发现任何具体的东西,但这很奇怪。我的意思是您已经知道,并且我认为这是一些动态查询,否则您编码它就知道一起查询什么。

    无论如何,作为一种变通方法,不确定是否可以,因为这取决于我们正在谈论的domainClasss,如果这是您已经实施的内容或正在考虑编写的内容,即如果可以添加自己的内容,则无论哪种情况都不会写获取所有相关 Realm 类
    //
    static String getDataSrc() {
    return 'data_source_a'
    }

    //or
    static boolean canQuery() {
    return true/false
    }

    您可以从任何地方进行检查,例如:
    boolean canQuery = UserAttributes.canQuery()
    String currentDataSource = UserAttributes.dataSrc

    由于它们是静态方法,因此不需要实例化。这意味着如果你有

    您不需要做的userObject(1):
    User user = User.get(1)
    if (user.canQuery()) {
    // this is ok
    }

    您可以直接在任何地方通过引用upperCase类名称及其方法来直接调用该方法。
    String currentDataSource = UserAttributes.dataSrc
    //Where this is exactly the same as above
    String currentDataSource = UserAttributes.getDataSrc()

    E2A:答案是:
    import org.grails.orm.hibernate.cfg.GrailsDomainBinder

    class TestController {
    //either this method
    def binder = new org.grails.orm.hibernate.cfg.GrailsDomainBinder().getMapping(Photos.class)
    println "binder : ${binder.table.name}"
    println "b: ${binder.datasources}"

    //Or this
    def dc=GrailsDomainBinder.getMapping(Photos.class)

    println "-dc is ${dc}"
    println "${dc.datasources}"
    }

    dc.datasources



    是一个列表,因此您需要比较列表。

    当然,我很傻,如果您在HQL中查询类似的内容,而您在其中给出动态表名$ {tableA} $ {tableB}

    您将需要访问实际的域类才能调用 GrailsDomainBinder
    So something like: def domainClass = grailsApplication.getDomainClass(domain).clazz
    将为您提供给定tableName的实际domainClass。但是您的域必须是完全合格的打包名称,这样将再次引起您的问题。
    如果查询 com.domain.users.tableAcom.domain.info.tableB
    因此,您可以改为在服务/ Controller 之外使用If:
    def domainClass=Holders.grailsApplication?.domainClasses?.find { it.clazz.simpleName == tableName }?.clazz

    如果要在 Controller 服务中声明grailsApplication,则不带Holder:
    def domainClass=grailsApplication?.domainClasses?.find { it.clazz.simpleName == tableName }?.clazz

    关于grails - 在Grails中,如何获得对特定类使用的数据源的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174023/

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