【发布时间】:2018-11-07 05:27:04
【问题描述】:
我的数据库中有 4 个表:
+-------------+
|Libraries |
+-------------+ . . . . . _________
|P code | |
+-------------+ -
. ^
. +---------------+
| |Persons |
| +---------------+
- |P name |
^ |FP library_code|
+-----------------+ +---------------+
|Books | .
+-----------------+ .
|P title | |
|FP library_code | |
+-----------------+ -
. ^
. +----------------+
| |Borrows |
+_______________|<+----------------+
|FP person_name |
|FP book_title |
|FP library_code |
+----------------+
P - primary key
FP - foreign primary key
_
^ - foreign key is part of primary key
Borrows 中的Persons 和Books 列library_code 应该相同(共享列)!
我的 java 代码如下:
@Entity
class Library {
@Id
private String code;
}
@Embeddable
class PersonId implements Serializable {
private String name;
private String library_code;
}
@Entity
class Person {
@EmbeddedId
private PersonId id;
}
@Embeddable
class BookId implements Serializable {
private String title;
private String library_code;
}
@Entity
class Book {
@EmbeddedId
private BookId id;
}
是否可以使用PersonId 和BookId 的共享library_code 列来实现这样的Borrow 实体,如何实现?:
@Embeddable
class BorrowId implements Serializable {
private PersonId person;
private BookId book;
}
@Entity
class Borrow {
@EmbeddedId
private BorrowId id;
}
注意:这个问题与数据库模型无关,模型已经提供,我无法更改它,我只需要找到如何将其映射到实体模型的最佳方法。
【问题讨论】:
-
鉴于您的
BorrowPK 是 3 列而不是 4 列(您的可嵌入实现意味着),我不会那样映射它。我只需为Borrow创建一个可嵌入的 3 列,并根据需要将值复制到其中,而不是想花哨。 -
我们离开的@Naros 作为备用选项。我们决定,对于我们的应用程序,最好创建问题中描述的结构。
-
您可以尝试在其中一个内部嵌入件上使用
@AttributeOverride将library_code标记为updatable=false,insertable=false,但我不确定这是否足以让持久性提供者不这样做抱怨重复的列名。标识符的某些方面确实会被某些提供程序覆盖(例如,不为空),因为 PK 列为空是没有意义的。 -
@Naros 我们将使用您的解决方案,因为我们没有找到更好的解决方案。但我仍然会在这里等待答案:)
标签: hibernate jpa spring-data spring-data-jpa