byte[] 在将其设置为 null 后未被清空

byte[] is not being nulled after setting it to null

我有一个使用 Hibernate 5.2 的项目。17.Final 和使用 MariaDB 的 Java 8。

我的实体有一个 byte[] 字段,我可以在其中将文件保存到数据库中。在我使用该字段将文件发送到 S3 后,我想删除其内容(将其设置为空),然后将实体保存到数据库,并将该字段设置为 null

我需要将该列保留在数据库中,因为这是一次升级,并且该列的条目具有非空值。

我尝试过的:

// first this:
invoiceDTO.setPdf(null);
// as the value of "PDF" is already null, invoice will have it also null
Invoice invoice = invoiceFaMapper.toEntity(invoiceDTO);
invoice = invoiceFaRepository.save(invoice);

调试时字段为空,但数据库中的值不为空。

// then I tried this:
byte[] pdf = null;
invoice.setPdf(pdf);

这也让我在数据库中留下了一个非空值,同样,在调试时 invoice 有一个非空值。

// last thing I tried was:
invoice.setPdf("".getBytes());

同样,它不是空的。

我错过了什么?

编辑:在 invoice = invoiceFaRepository.save(invoice); 之后,这是 byte[] 字段的值。

如果我正在调试和慢慢来,该字段设置为空,如果没有断点,它不会设置为空,而是设置为以前的值。

我什至在已经保存它以使其为空后尝试过这个,但无济于事。

invoice.setPdf(null);
invoiceFaRepository.save(invoice);

EDIT2:Invoice.java(相关)

(...)

@Lob
@Column(name = "pdf")
private byte[] pdf;

(...)

public byte[] getPdf() {
    return pdf;
}

public Invoice pdf(byte[] pdf) {
    this.pdf = pdf;
    return this;
}

public void setPdf(byte[] pdf) {
    this.pdf = pdf;
}

将对象保存到数据库后,我重定向到该对象。由于发票有很多行,我查询发票及其行

Optional<InvoiceDTO> invoiceDTO = invoiceService.findOneWithLines(id);

在那个方法里面我有这样的东西:

    @Override
    public Optional<InvoiceFaDTO> findOneWithLines(long id) {
        Optional<Invoice> i = invoiceFaRepository.findById(id);
        i.ifPresent(invoice -> {
            if (invoice.getAttachmentUrl() != null) {
                invoice.setPdf(amazonService.downloadFile(invoice.getAttachmentUrl()).toByteArray());
            }
        });
        return i.map(invoiceFaMapper::toDto);
    }

问题是无论我在括号内做什么都会存储在数据库中,我不知道为什么(我没有调用存储库,所以为什么要保存它?)。

我通过编辑 i.ifPresent(invoice -> { 行外的字段解决了这个问题。

编辑:Service class 注释为 @Transactional,添加 @Transactional(readOnly = true) 确实解决了问题。