gpt4 book ai didi

jpa - @OneToOne 单向和双向

转载 作者:行者123 更新时间:2023-12-01 18:28:37 27 4
gpt4 key购买 nike

我有两个例子,第一个是@OneToOne单向映射,第二个是双向映射。在单向映射中,拥有方表必须包含引用对方表id的连接列;那么在双向中,它们都必须包含彼此的外键列。但是使用自动生成策略生成数据库模式后,两个示例对数据库模式的效果相同。单向映射是正常的,但双向示例只包含一个外键列,但必须涉及彼此的外键!

单向映射

@Entity
public class Customer43 {

@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@OneToOne
@JoinColumn(name = "address_fk")
private Address43 address;

// Getters, Setters and Constructors.
}

@Entity
public class Address43 {

@Id
@GeneratedValue
private Long id;
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
private String country;

// Getters, Setters and Constructors.
}

双向映射

@Entity
public class Customer44 {

@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@OneToOne
@JoinColumn(name = "address_fk")
private Address43 address;

// Getters, Setters and Constructors.
}

@Entity
public class Address44 {

@Id
@GeneratedValue
private Long id;
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
private String country;
@OneToOne(mappedBy = "address")
private Customer44 customer;

// Getters, Setters and Constructors.
}

为什么数据库模式输出相同以及为什么双向映射表现得像单向?

最佳答案

因为你不明白双向 OneToOne 是如何映射的。您不需要两个外键。单个表足以在两个表之间执行双向联接:

select a.* from address a inner join customer c on c.addressId = a.id;
select c.* from customer c inner join address a on c.addressId = a.id;

关联是单向或双向的事实不会改变表的链接方式。它只是更改映射,并允许在两个方向上导航关联。

在双向关联中,您总是有一个拥有方(它告诉如何映射关联,使用哪个连接列)和一个反面,您只需说:我是关联的另一方,即目标实体中此字段(mappedBy 属性值中的字段)映射。

关于jpa - @OneToOne 单向和双向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9420916/

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