[英]can someone please explain me @MapsId in hibernate?
有人可以在休眠中向我解釋@MapsId
嗎? 我很難理解它。
如果可以用一個例子來解釋它並且它最適用於哪種用例,那就太好了?
這是Object DB 的一個很好的解釋。
指定 ManyToOne 或 OneToOne 關系屬性,該屬性提供 EmbeddedId 主鍵、EmbeddedId 主鍵內的屬性或父實體的簡單主鍵的映射。 value 元素指定關系屬性對應的組合鍵中的屬性。 如果實體的主鍵與關系引用的實體的主鍵的 Java 類型相同,則不指定 value 屬性。
// parent entity has simple primary key
@Entity
public class Employee {
@Id long empId;
String name;
...
}
// dependent entity uses EmbeddedId for composite key
@Embeddable
public class DependentId {
String name;
long empid; // corresponds to primary key type of Employee
}
@Entity
public class Dependent {
@EmbeddedId DependentId id;
...
@MapsId("empid") // maps the empid attribute of embedded id
@ManyToOne Employee emp;
}
在此處閱讀API 文檔。
我發現這個注釋也很有用:hibernate 注釋中的@MapsId
將一列映射到另一個表的列。
它還可用於在 2 個表之間共享相同的主鍵。
例子:
@Entity
@Table(name = "TRANSACTION_CANCEL")
public class CancelledTransaction {
@Id
private Long id; // the value in this pk will be the same as the
// transaction line from transaction table to which
// this cancelled transaction is related
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_TRANSACTION", nullable = false)
@MapsId
private Transaction transaction;
....
}
@Entity
@Table(name = "TRANSACTION")
@SequenceGenerator(name = "SQ_TRAN_ID", sequenceName = "SQ_TRAN_ID")
public class Transaction {
@Id
@GeneratedValue(generator = "SQ_TRAN_ID", strategy = GenerationType.SEQUENCE)
@Column(name = "ID_TRANSACTION", nullable = false)
private Long id;
...
}
正如他在他的教程中解釋 Vladimir 的那樣,映射 @OneToOne 關系的最佳方法是使用 @MapsId。 這樣,您甚至不需要雙向關聯,因為您始終可以使用父實體標識符獲取子實體。
恕我直言,考慮@MapsId
的最佳方式是當您需要在 an:m 實體中映射復合鍵時。
例如,一個客戶可以有一個或多個顧問,一個顧問可以有一個或多個客戶:
您的實體將是這樣的(偽 Java 代碼):
@Entity
public class Customer {
@Id
private Integer id;
private String name;
}
@Entity
public class Consultant {
@Id
private Integer id;
private String name;
@OneToMany
private List<CustomerByConsultant> customerByConsultants = new ArrayList<>();
public void add(CustomerByConsultant cbc) {
cbc.setConsultant(this);
this.customerByConsultant.add(cbc);
}
}
@Embeddable
public class ConsultantByConsultantPk implements Serializable {
private Integer customerId;
private Integer consultantId;
}
@Entity
public class ConsultantByConsultant {
@EmbeddedId
private ConsultantByConsultantPk id = new ConsultantByConsultantPk();
@MapsId("customerId")
@JoinColumn(insertable = false, updatable = false)
Customer customer;
@MapsId("consultantId")
@JoinColumn(insertable = false, updatable = false)
Consultant consultant;
}
映射這樣,JPA自動地插入Customer
和Consultant
IDS在EmbeddableId
每次保存顧問。 因此,您無需手動創建ConsultantByConsultantPk
。
MapsId 允許您在兩個不同的實體/表之間使用相同的主鍵。 注意:當您使用 MapsId 時, CASCADE.ALL
標志變得無用,您需要確保您的實體是手動保存的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.