在实施@OneToMany双向关系时,有很多方法会搞砸。这里说明一下最佳实践方式:
关键点:
源代码可以在 这里 找到 。
父类: @Entity <b>public</b> <b>class</b> Tournament implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) <b>private</b> Long id; <b>private</b> String name; @OneToMany(cascade = CascadeType.ALL, mappedBy = <font>"tournament"</font><font>, orphanRemoval = <b>true</b>) <b>private</b> List<TennisPlayer> tennisPlayers = <b>new</b> ArrayList<>(); </font>
子类: @Entity <b>public</b> <b>class</b> TennisPlayer implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) <b>private</b> Long id; <b>private</b> String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = <font>"tournament_id"</font><font>) <b>private</b> Tournament tournament; <b>public</b> Long getId() { <b>return</b> id; } <b>public</b> <b>void</b> setId(Long id) { <b>this</b>.id = id; } <b>public</b> String getName() { <b>return</b> name; } <b>public</b> <b>void</b> setName(String name) { <b>this</b>.name = name; } <b>public</b> Tournament getTournament() { <b>return</b> tournament; } <b>public</b> <b>void</b> setTournament(Tournament tournament) { <b>this</b>.tournament = tournament; } @Override <b>public</b> <b>boolean</b> equals(Object obj) { <b>if</b> (<b>this</b> == obj) { <b>return</b> <b>true</b>; } <b>if</b> (!(obj instanceof TennisPlayer)) { <b>return</b> false; } <b>return</b> id != <b>null</b> && id.equals(((TennisPlayer) obj).id); } @Override <b>public</b> <b>int</b> hashCode() { <b>return</b> 2018; } } </font>