映射仅由不带@IdClass或@EmbeddedId的复合PK组成的类
我有两个带有简单 PK 的表 A
和 B
。
@Entity
public class A {
@Id
public int idA;
}
@Entity
public class B {
@Id
public int idB;
}
我想映射一个新的关联类 AB,它仅存储 A
和 B
之间的关系,并使用复合 PK idA
+idB< /代码>。
AB
没有任何额外的列,只有 idA
和 idB
之间的关系。
是否可以使用单个类来映射 AB
?我想避免创建一个新的 ABId
类只是为了将其用作 AB
@IdClass 或 @EmbeddedId
>,并且我不想将其与 A
或 B
上的 @ManyToMany
关联映射。
I've got two tables A
and B
with simple PK's.
@Entity
public class A {
@Id
public int idA;
}
@Entity
public class B {
@Id
public int idB;
}
I want to map a new association class AB that simply stores the relations between A
and B
, with composite PK idA
+idB
. AB
doesn't have any extra columns, just the relation between idA
and idB
.
Is it possible to map AB
using a single class? I want to avoid having to create a new ABId
class just to use it as @IdClass
or @EmbeddedId
in AB
, and I don't want to map this with a @ManyToMany
association on A
or B
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要映射这样的连接表呢?只需在 A 和 B 之间使用多对多关联。然后,当您向 A 中包含的 B 列表中添加 B 或从中删除 B 时,将自动处理该连接表。
请参阅 http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e11402
如果你真的想这样做,那么只需映射两个ID与 @Id 表示法。主类将是实体类本身(必须是可序列化的),如 休眠参考文档。请注意,这是 Hibernate 特定的。
Why do you want to map such a join table? Just use a ManyToMany association between A and B. This join table will then be handled automatically when you'll add/remove a B to/from the list of Bs contained in A.
See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e11402
If you really want to do that, then just map the two IDs with the @Id notation. The primary class will be the entity class itself (which must be serializable), as explained in the hibernate reference documentation. Note that this is Hibernate-specific.
如果 @JBNizet 的 建议有效。不幸的是,有一个旧错误,这使得我无法在版本中采用它我使用(3.3.1-GA)
我终于通过定义内部静态ID类并将其用作
@IdClass
来解决这个问题:这样我就不必定义一个新的公共类, 和我不必修改映射文件来包含 ID 类。
It would be nice if @JBNizet 's suggestion worked. Unfortunately, there's an old bug which makes it impossible to adopt it in the version I'm using (3.3.1-GA)
I've finally sorted this out by defining an inner static ID class and using it as
@IdClass
:This way I don't have to define a new public class, and I don't have to modify the mappings file to include the ID class.