为什么一对多关联不能是双向的而应该是单向的?

why One-To-Many association cannot be Bidirectional and it should just be Unidirectional?

我正在尝试了解 JPAHibernate,并且我正在尝试了解一些数据库术语。

在 youtube 上的 a video 中,老师(在 2:42)说:

One-To-Many is only Unidirectional.

她说假设这两个 class:

class Person {

    List<Address> addresses;

}


class Address {

    Person p;

}

她说:

this is One-To-Many. but Address cannot have a collection of Person because if it has a collection of Person, it's going to be Many-To-Many.

但我觉得她不对,因为我们可以有这两个:

thePerson.getAddresses().get(i);

anAddress.getPerson();

当我们能有这两个语句时,那就是双向。那为什么她说可以单向?

Bidirectional 得出这样结论的确切定义是什么?

你说的对,她说的不对。各种关系都可以去单向或双向。

在子端,您必须使用@JoinColumn 注释该字段。

在父端,你必须使用@OneToMany注解的属性 mappedBy。

示例:

@OneToMany(mappedBy = "user")
private List<Address> addresses;

@ManyToOne
@JoinColumn
private User user;

这是一个很好的讲座。

https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/

首先,任何关系都可以是单向双向,这完全取决于您希望如何显示或检索数据,以及您的业务规则。

When we can have these two statements, then it is Bidirectional. Then why she said it can be just Unidirectional?

ORMsobject oriented 方法(如 Hibernate)与 relational database 中表和关系的定义方式之间也存在很大的不匹配。她可以说得对,因为从数据库的角度来看,关系默认是 单向的

单向双向的区别在于您可以访问您关系另一方的记录.

What is Bidirectional's exact definition with which she came to such a conclusion?

在您的示例中,我们可以这样解释您的关系:

  • 单向:你可以从人那里得到你所有的地址,但不是相反的

     class Person {
    
         @OneToMany
         List<Address> addresses;
    
     }
    
     class Address {
    
         // Here you don't add the ManyToOne
         Person p;
     }
    
  • 双向:你可以从一个人得到你所有的地址,从一个地址得到一个人

     class Person {
    
         @OneToMany
         List<Address> addresses;
     }
    
     class Address {
    
         @ManyToOne
         Person p;
     }
    

看看下面的链接:

Difference between unidirectional and bidirectional relational relationship

https://www.baeldung.com/spring-data-rest-relationships