这是我的课程,
@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已生成。
如何绕过这个问题,谢谢。