單向:
<code class="java">class Foo { private Bar bar; } class Bar { }</code>
雙向(Foo 類管理):
<code class="java">class Foo { @OneToOne(cascade = CascadeType.ALL) private Bar bar; } class Bar { @OneToOne(mappedBy = "bar") private Foo foo; }</code>
使用使用者管理連接表的單向:
<code class="java">class Foo { @OneToMany @JoinTable(name = "FOO_BAR", joinColumns = {@JoinColumn(name = "fooId")}, inverseJoinColumns = {@JoinColumn(name = "barId")}) private List<Bar> bars; } class Bar { // No corresponding mapping to Foo.class } @Entity @Table(name = "FOO_BAR") class FooBar { private UUID fooBarId; private Foo foo; private Bar bar; }</code>
使用外鍵對映的雙向:
<code class="java">class Foo { @OneToMany(mappedBy = "bar") private List<Bar> bars; } class Bar { @ManyToOne @JoinColumn(name = "fooId") private Foo foo; }</code>
使用Hibernate 託管連接表的雙向:
<code class="java">class Foo { @OneToMany @JoinTable(name = "FOO_BAR", joinColumns = {@JoinColumn(name = "fooId")}, inverseJoinColumns = {@JoinColumn(name = "barId")}) private List<Bar> bars; } class Bar { @OneToMany @JoinTable(name = "FOO_BAR", joinColumns = {@JoinColumn(name = "barId")}, inverseJoinColumns = {@JoinColumn(name = "fooId")}) private List<Foo> foos; }</code>
使用雙向使用者管理的聯接表:
<code class="java">class Foo { @OneToMany(mappedBy = "bar") private List<FooBar> bars; } class Bar { @OneToMany(mappedBy = "foo") private List<FooBar> foos; } @Entity @Table(name = "FOO_BAR") class FooBar { private UUID fooBarId; private Foo foo; private Bar bar; }</code>
以上是如何使用註解定義 Hibernate 和 Spring 中的關係?的詳細內容。更多資訊請關注PHP中文網其他相關文章!