Hibernate/JPA中如何正确使用@OneToMany双向关系?

栏目: Java · 发布时间: 5年前

内容简介:在实施@OneToMany双向关系时,有很多方法会搞砸。这里说明一下最佳实践方式:关键点:源代码可以在

在实施@OneToMany双向关系时,有很多方法会搞砸。这里说明一下最佳实践方式:

关键点:

  • 始终从父级到子级实现级联
  • 在父类上使用mappedBy
  • 在父类上使用orphanRemoval以删除父类不再引用的子类
  • 在父类上使用helper方法可以使关联的两端保持同步
  • 始终使用延迟提取
  • 使用自然/业务key或使用实体标识符并覆盖equals(),hashCode()如此 处所示

源代码可以在 这里 找到  。

父类:
@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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

共鸣:内容运营方法论

共鸣:内容运营方法论

舒扬 / 机械工业出版社 / 2017-5-8 / 59.00

近5年来网络信息量增长了近10倍,信息极度过剩。移动互联网以碎片化、强黏度以及惊人的覆盖率给传统的商业环境带来了巨大的影响,向陈旧的广告、公关、媒体行业展开了深度的冲击。 传统的以渠道为中心的传播思想几近失效,优秀内容成为了各行业最稀缺的资产,这是时代赋予内容生产者的巨大机会。本书作者在多年经验和大量案例研究的基础上,总结出了移动互联网时代的内容运营方法论——共鸣,它将告诉我们如何收获核心粉......一起来看看 《共鸣:内容运营方法论》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具