Grails 技巧 - Grails and Hibernate

1.使用Hibernate XML映射文件java

當遷移歷史的基於Hibernate的項目到grails,在grails-app/conf/hibernate目錄下創hibernate.cfg.xmlsession

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Example mapping file inclusion -->
        <mapping resource="org.example.Book.hbm.xml"/>
        …
    </session-factory>
</hibernate-configuration>

當hibernate.cfg.xml存放的位置不符合要求時,能夠grails-app/conf/DataSource.groovy下配置其它位置app

hibernate {
    config.location = "file:/path/to/my/hibernate.cfg.xml"
}

或者列表性能

hibernate {
    config.location = ["file:/path/to/one/hibernate.cfg.xml",
                       "file:/path/to/two/hibernate.cfg.xml"]
}

2.約束條件 (Constraints).net

若是歷史Domain java類 是org.example.Bookhibernate

則建立groovy腳本 src/java/org/example/BookConstraints.groovycode

增長標準的GORM constraints到腳本中xml

constraints = {
    title blank: false
    author blank: false
}

這樣org.example.Book 就具有了grails的驗證能力對象

3.多數據源get

若是存在多個數據源,grails-app/conf/hibernate/hibernate.cfg.xml使用默認數據源

hibernate.cfg.xml能夠增長數據源前綴

grails-app/conf/hibernate/ds2_hibernate.cfg.xml

上面配置會使用 ds2 數據源

4.Session.createFilter()

Session過濾器對Domain關聯的集合對象用處很是大,能夠提升集合訪問性能

class Branch {
    String name
    static hasMany = [visits: Visit]

    int getVisitCount() {
        visits == null ? 0 : withSession {
            it.createFilter(visits, 'select count(*)').uniqueResult()
        }
    }
}


class Branch {
    String name
    List visits
    static hasMany = [visits: Visit]

    List<Visit> getVisitsByPage(int pageSize, int pageNumber) {
        Branch.withSession { session ->
            session.createFilter(visits, '')
            .setMaxResults(pageSize)
            .setFirstResult(pageSize * pageNumber)
            .list()
        }
    }
}
相關文章
相關標籤/搜索