我怎么能在班上有2个相同类型的对象?

时间:2012-03-06 08:39:24

标签: java database oracle hibernate object

我有一个类需要有2个相同类型的对象。我正在使用Hibernate,它根据我的类创建我的数据库模式。

属性:

private User user;
private User keyAccountManager;

的getter / setter:

@ManyToOne
@JoinColumn(name = "userId")
@ForeignKey(name = "license_users_fk")
public User getUser() {
    return user;
}

@ManyToOne
@JoinColumn(name = "userId")
@ForeignKey(name = "license_kam_fk")
public User getKeyAccountManager() {
    return keyAccountManager;
}

如果我这样做,我会收到此错误:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: License column: userId (should be mapped with insert="false" update="false")
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:670)
    at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:692)
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:714)
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:468)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:215)
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1135)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1320)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
    ... 55 more

当我将其更改为@JoinColumn(name = "userId", insertable=false, updatable=false)时,它会毫无问题地部署,该列是在数据库中创建的,但是当我调用setKeyAccountManager()时,该值未在数据库中设置。

如何在此课程中拥有2个相同类型的对象?谢谢!

2 个答案:

答案 0 :(得分:2)

问题不在于他们属于同一类。问题是它们都映射到userId列。

Hibernate期望getKeyAccountManager()表示userId列或getUser(),而不是两者。

也许您引用了错误的列?

答案 1 :(得分:2)

假设需要具有2个用户类型的类映射到名为License的表

name

@JoinColumn属性定义了License表中具有User表外键约束的列名。它绝对不是指User表的主键,因为这些信息应该在User类本身上注释。

因此,在您的情况下,您应该使用不同的名称定义@JoinColumn,例如:

@ManyToOne
@JoinColumn(name = "user_Id")
@ForeignKey(name = "license_users_fk")
public User getUser() {
    return user;
}

@ManyToOne
@JoinColumn(name = "key_acct_mgr_id")
@ForeignKey(name = "license_kam_fk")
public User getKeyAccountManager() {
    return keyAccountManager;
}

然后,它映射到下表结构:

==================================================
| License                                        |
==================================================
|id (Primary key of table License)               |
|user_Id (Foreign key to the User Table)         |
|key_acct_mgr_id (Foreign key to the User Table) |
==================================================