我有两个例子,首先是@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.
}
为什么数据库模式输出相同,为什么双向映射就像单向?
答案 0 :(得分:19)
因为您不了解双向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
属性值中的字段)映射。
答案 1 :(得分:4)
我刚做了一个实验。如果您只是在下面执行此操作,则两个表都将具有外键:
@OneToOne
private Address43 address;
@OneToOne
private Customer44 customer;
现在您不需要进行连接。我不确定这是不是一个好习惯。只要确保你没有CASCADES。