gpt4 book ai didi

java - Hibernate 中 @MapsId 注解的用途

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:41 26 4
gpt4 key购买 nike

我想了解 @MapsId 注释在 Hibernate 中有什么不同。我已经阅读了 Hibernate 文档,但由于我是 Hibernate 的新手,我仍然对那里给出的解释感到困惑。

document是这样说的:

@Entity
class Customer {
@EmbeddedId CustomerId id;
boolean preferredCustomer;

@MapsId("userId")
@JoinColumns({
@JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
@JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
})
@OneToOne User user;
}

@Embeddable
class CustomerId implements Serializable {
UserId userId;
String customerNumber;

//implements equals and hashCode
}

@Entity
class User {
@EmbeddedId UserId id;
Integer age;
}

@Embeddable
class UserId implements Serializable {
String firstName;
String lastName;

//implements equals and hashCode
}

In the embedded id object, the association is represented as the identifier of the associated entity. But you can link its value to a regular association in the entity via the @MapsId annotation. The @MapsId value correspond to the property name of the embedded id object containing the associated entity's identifier. In the database, it means that the Customer.user and the CustomerId.userId properties share the same underlying column (user_fk in this case).

我不清楚这个解释说的是什么,所以我厌倦了在我的配置文件中将 hbm2ddl 设置为 create 并且我观察到这些:

对于 Customer 实体上的 @MapsId 和 @JoinColumns,DDL 语句是:

Hibernate: create table CUSTOMER (customerNumber varchar2(255 char) not null, preferredCustomer number(1,0) not null, userfirstname_fk varchar2(255 char) not null, userlastname_fk varchar2(255 char) not null, primary key (customerNumber, userfirstname_fk, userlastname_fk))
Hibernate: create table USER (firstName varchar2(255 char) not null, lastName varchar2(255 char) not null, age number(10,0), primary key (firstName, lastName))
Hibernate: alter table CUSTOMER add constraint UK_xxxx unique (userfirstname_fk, userlastname_fk)
Hibernate: alter table CUSTOMER add constraint FK_xxxx foreign key (userfirstname_fk, userlastname_fk) references TBL_USER

如果我删除@MapsId 和@JoinColumns 注释,我会看到这些:

Hibernate: create table CUSTOMER (customerNumber varchar2(255 char) not null, firstName varchar2(255 char), lastName varchar2(255 char), preferredCustomer number(1,0) not null, user_firstName varchar2(255 char), user_lastName varchar2(255 char), primary key (customerNumber, firstName, lastName))
Hibernate: create table USER (firstName varchar2(255 char) not null, lastName varchar2(255 char) not null, age number(10,0), primary key (firstName, lastName))
Hibernate: alter table CUSTOMER add constraint FK_xxxx foreign key (user_firstName, user_lastName) references TBL_USER

请帮助我理解 Hibernate 中 @MapsId 注释的概念。

最佳答案

@MapsId 将共享主实体的主键作为子实体的主键,无需在子实体中插入外键。 Hibernate 将映射两个实体的 PK 并向我们返回一个对象。

关于java - Hibernate 中 @MapsId 注解的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25269763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com