1

保存我的实体时,我得到了一个非常奇怪的 NullPointerException,我似乎无法弄清楚为什么。

java.lang.NullPointerException: null
at org.hibernate.type.AbstractType.getHashCode(AbstractType.java:129)
at java.base/java.util.stream.Collectors.lambda$groupingBy$53(Collectors.java:1127)
at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1654)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
at org.hibernate.collection.internal.PersistentBag.groupByEqualityHash(PersistentBag.java:196)
at org.hibernate.collection.internal.PersistentBag.equalsSnapshot(PersistentBag.java:151)
at org.hibernate.engine.spi.CollectionEntry.dirty(CollectionEntry.java:158)
at org.hibernate.engine.spi.CollectionEntry.preFlush(CollectionEntry.java:182)
at org.hibernate.event.internal.AbstractFlushingEventListener.lambda$prepareCollectionFlushes$0(AbstractFlushingEventListener.java:195)
at org.hibernate.engine.internal.StatefulPersistenceContext.forEachCollectionEntry(StatefulPersistenceContext.java:1091)
at org.hibernate.event.internal.AbstractFlushingEventListener.prepareCollectionFlushes(AbstractFlushingEventListener.java:194)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:86)
at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:50)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108)
at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1323)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1403)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1558)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1526)
at org.hibernate.query.Query.getResultList(Query.java:165)
[...] the rest was cut for readability (if you think it's really important, I'll edit and add the whole exception, but I think it's the first line that says it all)

这是由于上述原因而引发的更高异常:

org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:542)

这个嵌套的:

Caused by: javax.persistence.RollbackException: Error while committing the transaction
    at org.hibernate.internal.ExceptionConverterImpl.convertCommitException

我整天都在兜圈子,试图弄清楚为什么会发生这种情况,而互联网没有帮助,因为大多数类似的问题仍未得到解答。更糟糕的是 Spring 的抽象使得它无法调试!

这是场景:我有一个EventEntity我正在尝试更新的,以及它的子实体EventAttachmentEntity。我已打开日志记录以跟踪正在发生的事情,并且几乎预期会发生:

  • 我已经更新了 eventEntity(更新 SQL 生成)
  • 我为更新的事件插入了新附件(插入使用正确 event_id 生成的 SQL)

然后奇怪的事情发生了,我的方法走到了尽头,然后发生了这个异常。

由于公开原因,该方法被抽象出来,但主要流程如下:

@Transactional(rollbackFor = Exception.class)
public void updateEvent(EventEntity event) {
    EventEntity updatedEvent = eventRepository.save(event);

    EventAttachmentEntity newAttachment = new EventAttachmentEntity(updatedEvent);
    // fill attachment [...]
    newAttachment.setEvent(updatedEvent);
    eventAttachmentRepository.save(newAttachment); 

    System.out.println("This line gets printed.");
}

所以首先我保存更新的父级,然后创建新的子级,设置父级,然后保存它。所有 SQL 都确认这是发生的情况。最后一行也会打印出来,这意味着以前的保存方法没有任何问题。然后它到了尽头,砰!例外。

这是我的实体:

@Entity
@Table(name = "event", schema = "xxx")
@DynamicUpdate
public class EventEntity {
    private long id;
    private Collection<EventAttachmentEntity> eventAttachments;

    // other properties abstracted

    @OneToMany(mappedBy = "event")
    public Collection<EventAttachmentEntity> getEventAttachments() {
        return this.eventAttachments;
    }

    public void setEventAttachments(Collection<EventAttachmentEntity> eventAttachments) {
        this.eventAttachments = eventAttachments;
    }
}
@Entity
@Table(name = "event_attachment", schema = "xxx")
public class EventAttachmentEntity {
    private long id;
    private String filename;
    private String contentType;
    private long filesize;
    private EventEntity event;

   // other properties abstracted

    @ManyToOne
    @JoinColumn(name = "event_id", referencedColumnName = "id", nullable = false)
    public EventEntity getEvent() {
        return event;
    }

    public void setEvent(EventEntity event) {
        this.event = event;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        EventAttachmentEntity that = (EventAttachmentEntity) o;
        return id == that.id &&
                filesize == that.filesize &&
                Objects.equals(filename, that.filename) &&
                Objects.equals(contentType, that.contentType);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, filename, contentType, filesize);
    }
}

我已经包含了 EventAttachmentEntity 的equals()hashCode()方法,因为异常显然发生在getHashCode(),但是当我将断点放在那里时,它实际上是调用 getHashCode 的 Object 为空。

重要说明:我检查了我的代码中的任何变量是否为空或没有正确自动装配 - 一切都很好。就像我说的那样,该方法本身运行平稳,直到它到达最后并尝试提交事务。那是它破裂的时候。

此外,当我尝试仅更新事件(不带附件)时,一切正常。我尝试过的另一种情况是保存此事件的类似关系(此处未显示),它也可以正常工作。所以它与附件有关,我无法弄清楚它是什么

同样奇怪的是,如果我@Transactional从这个方法中删除,它会抛出同样的异常。没有@Transactional标记的方法正在调用updateEvent(),所以我不确定这是怎么发生的。

拜托,我需要任何关于可能是什么问题的建议,所以我可以尝试一下,因为现在我几乎碰壁了,无法继续。

4

2 回答 2

0

您还没有显示整个代码,我们只能猜测您那里有什么。根据 tp 显示的代码,成员变量EventEntity.eventAttachments未初始化。当您尝试保留此类实体时,这可能会导致 NPE。

解决方案

初始化它,例如如下:

private Collection<EventAttachmentEntity> eventAttachments = new HashSet<>();

还要setEventAttachments确保eventAttachment无论将什么参数传递给此设置器,它都不会为空。

于 2019-12-25T17:35:40.130 回答
0

InupdateEvent(EventEntity updatedEvent)方法updatedEvent被持久化到 database eventRepository.save(updatedEvent),但是S save(S entity)方法的文档说:

保存给定的实体。使用返回的实例进行进一步的操作,因为保存操作可能已经完全改变了实体实例。

从您到目前为止发布的代码看来,您似乎没有save按照建议使用方法实体实例返回的方法:

eventRepository.save(updatedEvent);

EventAttachmentEntity newAttachment = new EventAttachmentEntity(updatedEvent);
// fill attachment [...]
newAttachment.setEvent(updatedEvent);

我不确定这是否可能是错误的原因,但处理更新的正确方法是这样的:

updatedEvent = eventRepository.save(updatedEvent); // update updatedEvent 

EventAttachmentEntity newAttachment = new EventAttachmentEntity(updatedEvent);
// fill attachment [...]
newAttachment.setEvent(updatedEvent);
于 2019-12-25T21:13:22.770 回答