gpt4 book ai didi

Java hibernate 一对一: which side should be the owner

转载 作者:行者123 更新时间:2023-12-02 10:02:19 26 4
gpt4 key购买 nike

所以我从这些简单的例子中学习,有 2 个表,USERS 和 USER_DETAILS,足够简单,每个用户都有 user_details 并且它是一对一的关系。所以这个样本是这样的,

@Entity
@Table(name = "USERS")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USR_ID")
private long id;

@Column(name = "USERNAME", nullable = false, unique = true)
private String username;

@Column(name = "PASSWORD")
private String password;

@OneToOne(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY)
private UserDetail userDetail;

//Setter and getter methods
}

@Entity
@Table(name = "USER_DETAILS")
public class UserDetail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USR_DET_ID")
private long id;

@Column(name = "FIRST_NAME")
private String firstName;

@Column(name = "LAST_NAME")
private String lastName;

@Column(name = "EMAIL")
private String email;

@Column(name = "DBO")
private LocalDate dob;

@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "USR_ID")
private User user;

//Setter and Getter methods
}

如果您查看mappedBy,它位于User 而不是UserDetails 中。

Q1: so USER is the owner, if it calls save(), 
USER_DETAILS table will be updated as well ?

Q2: same examples put mappedBy in the USER_DETAILS side,
why people want to do this ?
How to determine which side to put mappedBy ?

感谢您的帮助!

最佳答案

Q2:相同的示例将mappedBy放在USER_DETAILS一侧,为什么人们要这样做?如何确定将mappedBy放在哪一边?

In a bidirectional relationship, each entity has a relationship field or property that refers to the other entity. Through the relationship field or property, an entity class’s code can access its related object. If an entity has a related field, the entity is said to “know” about its related object.

您的示例中存在双向一对一关系。 UserUserDetail 实体都有一个关系字段。在两个实体上指定的 @OneToOne 注释。

For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

关系的所有者是 UserDetail 实体。所有者有 @JoinColumn 注释来指定外键 (USR_ID)。

关系的反面(User)具有mappedBy 属性。

Q1:所以 USER 是所有者,如果它调用 save(),USER_DETAILS 表也会更新吗?

在您的示例中,UserDetail 是所有者。因此保存过程:

User user = new User();  // Ignoring the constructor parameters...
UserDetail userDetail = new UserDetail();

user.setUserDetail(userDetail);
userDetail.setUser(user);

userRepository.save(user);

您只需要保存父级。这也将拯救 child 。

关于Java hibernate 一对一: which side should be the owner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55538328/

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