在Hibernate中映射大字段(byte [])的最佳方法

时间:2020-03-03 11:06:24

标签: java hibernate hibernate-mapping

我有一个实体模型,我想在其中存储有关RTU及其运行固件的信息。我需要将固件存储在数据库中的字节数组中,因此可以远程重新安装固件。我的第一种方法是这样的:

RTU
---
rtuId int (PK)
firmwareId int (FK)
.
.
.

Firmware
--------
firmwareId int (PK)
code int
firmware byte[]
.
.
.

public class Rtus {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "rtuid")
    private long rtuId;

    @JoinColumn(name = "firmwareid", referencedColumnName = "firmwareid")
    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    private Firmwares firmware;

    @Transient
    private Integer firmwareId;

    .
    .
    .

}

public class Firmwares implements Serializable, Cloneable {

    @Id
    @Basic(optional = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "firmwareid")
    private Integer firmwareId;   

    @Basic(optional = false)
    @Column(name = "firmware")
    private byte[] firmware;

    @Basic(optional = false)
    @Column(name = "code", unique = true)
    private int code;   


    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "firmware")
    @JsonIgnore
    private Collection<Rtus> rtuCollection;

    .
    .
    .
}

这里的问题是,在检索RTU对象时,在大多数情况下,它需要包含固件的代码,因此对于每个检索到的对象,我也需要显式获取Firmware对象。该对象包含一个大字节数组,因此此负载将消耗大量内存。

因此,我目前的方法是使用@OneToOne关系将字节数组与主要实体分离成一个新的实体,并仅在有必要发送时才加载它:

Firmware
--------
firmwareId int (PK)
code int
.
.
.

FirmwareBinary
--------------
firmwareId int (PFK)
firmware byte[]

我做了一些研究,似乎即使指定了FetchType.LAZY,也无法懒洋洋地获取@OneToOne双向关联的父级,所以我遇到了与以前相同的问题。

当您有一个非常大的字段要与对象的其余部分保持分离,并在明确需要时加载到内存中时,实现这种情况的最常见设计是什么?

0 个答案:

没有答案
相关问题