JPA – @ onetoone unidirectional and bidirectional

I have two examples, the first is @ onetoone one-way mapping and the second two-way mapping In one-way mapping, the owner table must contain connection columns that reference the IDs of other tables; Then in bidirectional, they must contain each other's foreign key columns However, after generating the database schema using the automatic generation strategy, the two examples have the same effect on the database schema One way mapping is normal, but the two-way example contains only one foreign key column, but it must involve each other's foreign keys!

Unidirectional mapping

@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.
}

Bidirectional mapping

@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.
}

Why is the database schema output the same, and why does bidirectional mapping behave like one-way mapping?

Solution

Because you don't know how to map two-way onetoone You don't need two foreign keys A single one is sufficient to perform a join between two tables in two directions:

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;

The fact that associations are unidirectional or bidirectional does not change how tables are linked together It simply changes the mapping and allows you to navigate the association in both directions

In a two-way Association, you always have an owner (which tells the association how to map and which connection column to use) and a reverse. You just need to say: I am the opposite field of the object mapping (the field in the mappingby attribute value)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>