Grails 技巧 - Grails and Hibernate

本文介绍了如何在Grails项目中集成Hibernate,包括使用Hibernate XML映射文件、配置多数据源、实现约束验证及利用Session.createFilter()方法优化查询性能等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用Hibernate XML映射文件

当迁移历史的基于Hibernate的项目到grails,在grails-app/conf/hibernate目录下创hibernate.cfg.xml

<?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下配置其它位置

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)

如果历史Domain java类 是org.example.Book

则创建groovy脚本 src/java/org/example/BookConstraints.groovy

增加标准的GORM constraints到脚本中

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

这样org.example.Book 就具备了grails的验证能力

3.多数据源

如果存在多个数据源,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()
        }
    }
}

转载于:https://my.oschina.net/linghuchong/blog/141325

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值