【问题标题】:Foreign key object as primary key外键对象作为主键
【发布时间】:2011-07-13 08:57:12
【问题描述】:

我有以下域类实体:

class AccountSupplier {

static mapping = {
     table 'MY_TABLE'
     version false

     // references-column-mapping
     accountReference: column:'REFACNTID'
     supplierReference column:'REFSUPID'

    // primary / foreign keys
    id generator: 'assigned', column: 'REFACNTID'
    id generator: 'assigned', column: 'REFSUPID'
}

Account accountReference
Supplier supplierReference

static constraints = {
    accountReference(insert:false, update:false, nullable:false)
    supplierReference(insert:false, update:false, nullable:false)
}
}

应该在 oracle 数据库中映射一个真实的表(已经存在并包含数千条记录。

当我想启动 grails 时,我得到以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageSource': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: AccountSupplier column: REFSUPID (should be mapped with insert="false" update="false")
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.codehaus.groovy.grails.commons.spring.ReloadAwareAutowireCapableBeanFactory.doCreateBean(ReloadAwareAutowireCapableBeanFactory.java:105)

这有什么问题?我需要修改相关实体吗?我不能为主键创建外键吗?

谢谢

【问题讨论】:

    标签: oracle grails grails-orm


    【解决方案1】:

    首先,通常的评论:外键不能用作主键。它会(并且可能已经)让你很头疼。如果你能改变它,就改变它。

    也就是说:您的问题是您向实体添加了两个 ID 生成器。我的猜测是 Grails 只支持每个实体一个(毕竟每个实体只能有一个主键)。

    我认为您在脑海中混合了数据库表和映射。映射不使用 ID。它只知道引用。你不应该关心某个地方有一个 ID。

    事实上,对于这个映射,您不应该使用任何 ID 生成器。将实例分配给字段时会自动分配 ID。如果您需要 ID 生成器,请将它们添加到 AccountSupplier 的映射中。

    【讨论】:

    • 谢谢。就像我说的数据库确实已经存在(并且其他应用程序已连接到它),所以我无法编辑模型。我删除了 ID 生成器并且它工作(部分)。我怎么能说 grails 他应该在引用的类中使用哪一列作为 ID? (当我使用 List() 时出现异常:java.sql.SQLSyntaxErrorException: ORA-00904: "THIS_"."ACCOUNT_REFERENCE_ID":
    • 告诉 Grails 引用表的主键。你只需要在课程本身(而不是在AccountSupplier)中这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多