【问题标题】:Is there a Hibernate supported in memory database that support GUID id columns?内存数据库中是否支持支持 GUID id 列的 Hibernate?
【发布时间】:2013-07-31 05:34:11
【问题描述】:

我正在开发一个 Grails 应用程序,我需要与现有数据库 (Oracle) 集成,该数据库使用 GUID 作为某些表的主键。 Grails 可以使用以下方法轻松处理此问题:

static mapping = {
    id generator: 'guid'
}

当我尝试使用内存数据库编写一些集成测试时,我的问题就出现了。是否有支持 GUID 主键列的内存数据库?如果没有,有没有办法在测试期间切换生成器值?

到目前为止,我已经测试了 Grails 提供的默认 H2 数据库,但没有成功。

【问题讨论】:

    标签: database hibernate grails grails-orm


    【解决方案1】:

    看起来 Hibernate 的 GUID 支持实际上只是为了包装 Oracle 的实现,因此它不可移植并且不适用于 H2。但它很简单,可以在任何地方使用您自己的。实现org.hibernate.id.IdentifierGenerator接口,例如

    package com.mycompany.myapp
    
    import org.hibernate.engine.SessionImplementor
    import org.hibernate.id.IdentifierGenerator
    
    class UuidIdentifierGenerator implements IdentifierGenerator {
    
       Serializable generate(SessionImplementor session, object) {
          UUID.randomUUID().toString()
       }
    }
    

    并将生成器属性更改为实现的完整类名:

    class MyDomainClass {
       String id
       // other fields
    
       static mapping = {
          id generator: 'com.mycompany.myapp.UuidIdentifierGenerator'
       }
    }
    

    【讨论】:

    • 感谢您的回答。我几乎被一个单元测试冲昏了头脑(模拟对象不抱怨 id 生成器),并没有真正编写集成测试。
    • 由于我正在与旧数据库集成,因此我最终更进一步并使用数据库 GUID(如果支持),否则我会退回到生成一个随机的。这是 IdentifierGenerator 类的要点:gist.github.com/pmcdaniel/6147616 感谢您的帮助!
    【解决方案2】:

    我是这样使用Hibernate hbm映射的:

    <id  name="id" column="id" >
        <generator class="guid"></generator>
    </id>
    

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 1970-01-01
      • 2023-03-30
      • 2014-03-04
      • 2013-08-20
      • 2017-03-11
      • 2020-08-18
      • 2010-09-07
      • 2016-11-10
      相关资源
      最近更新 更多