@PostPersist @OneToMany mappedBy问题

时间:2017-08-04 06:08:19

标签: hibernate spring-data-jpa

这是我的课程,

@Entity
class Advertisement {
    @Id
    @GeneratedValue
    private long id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "advertisement")
    private List<AdvertisementCoupon> coupons = new ArrayList<>();

    @PostPersist
    public void onPostPersist() {
 EventPublisher.CURRENT.publishEvent(new AdvertisementCreatedEvent(this));
    }
}

@Entity
class AdvertisementCoupon {
    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    private Advertisement advertisement;
}

class TimelineEventListener {

    @EventListener
    public void onAdvertisementCreated(AdvertisementCreatedEvent event){

        if (timelineRepository.existsByUserIdAndAdvertisementId(
            event.getAdvertisement().getCreatedUser().getId(), 
            event.getAdvertisement().getId())) {

            return;
        }

        TimelineAdvertisement timelineAdvertisement = new TimelineAdvertisement(event.getAdvertisement().getCreatedUser(), event.getAdvertisement());
        timelineRepository.save(timelineAdvertisement);
    }
}

调用@PostPersist时,只插入广告(我打印sql)。

onAdvertisementCreated方法中,当调用timelineRepository.existsByUserIdAndAdvertisementId时,会插入AdvertisementCoupon,但会引发Column 'advertisement_id' cannot be null异常。 广告ID已生成。

如何绕过这个问题,谢谢。

0 个答案:

没有答案