I have two entity classes: Fund and FundMetadata, FundMetadata mapped to Fun Fund as one-to-one relation with @MapsId. When I try to save Fund with populated FundMetadata (by FundServiceImpl#save method) the next exception appears:
{code} Caused by: org.hibernate.id.IdentifierGenerationException: null id generated for:class org.gh.db.persistence.metadata.FundMetadata at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125) at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:192) at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135) at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:827) {code}
{code:java} @Entity @Table(name = "Fund_Metadata", schema = "metadata") class FundMetadata { private Integer id; private Fund fund; private LocalDateTime externalNotesEditDate;
@Id public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
@MapsId @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "fundId", nullable = false, updatable = false) public Fund getFund() { return fund; }
public void setFund(Fund fund) { this.fund = fund; }
@Column(name = "externalNotesEditDate", columnDefinition = "datetime", nullable = false) public LocalDateTime getExternalNotesEditDate() { return externalNotesEditDate; }
public void setExternalNotesEditDate(LocalDateTime externalNotesEditDate) { this.externalNotesEditDate = externalNotesEditDate; } }
@Entity @Table(name = "Fund") class Fund { private Integer entityId; private FundMetadata metadata;
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getEntityId() { return entityId; }
public void setEntityId(Integer entityId) { this.entityId = entityId; }
@PrimaryKeyJoinColumn @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) public FundMetadata getMetadata() { return metadata; }
public void setMetadata(FundMetadata metadata) { this.metadata = metadata; } }
@Service class FundServiceImpl implements FundService { private final FundRepository fundRepository;
public FundServiceImpl(FundRepository fundRepository) { this.fundRepository = fundRepository; }
public Fund save(Fund entity) { final FundMetadata metadata = new FundMetadata(); metadata.setFund(entity); metadata.setExternalNotesEditDate(LocalDateTime.now()); entity.setMetadata(metadata); return fundRepository.save(entity); } } {code} |
|