单向:
<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中文网其他相关文章!