jpa – @OneToOne单向和双向

前端之家收集整理的这篇文章主要介绍了jpa – @OneToOne单向和双向前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个例子,首先是@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;

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

在双向关联中,您始终拥有一个拥有方(它告诉关联如何映射,使用哪个连接列)和一个反面,您只需说:我是该对象映射的对方字段(mappingBy属性值中的字段).

原文链接:/java/123345.html

猜你在找的Java相关文章