繁体   English   中英

我班上怎么有两个相同类型的对象?

[英]How can I have 2 objects of the same type in my class?

我有一个需要两个相同类型的对象的类。 我正在使用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个相同类型的对象? 谢谢!

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

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

也许您引用的列错误?

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

@JoinColumn name属性定义许可证表中具有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) |
==================================================

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM