Home > Net >  Spring JPA inserts null foreign key on save (OneToOne Bidirectional Mapping)
Spring JPA inserts null foreign key on save (OneToOne Bidirectional Mapping)

Time:01-19

I'm having issues with a OneToOne Bidirectional Mapping using Spring JPA (Kotlin). I have an Event and an EventAddress associated to it. Each Event can have one EventAddress and similarly each EventAddress can have one Event associated with it. I am using the CrudRepository interface to insert an Event, in which I first assign an EventAddress to the Event and then save it using the EventsRepository save() method.

Here are stripped down versions of my models:

@Entity(name = "events")
@EntityListeners(AuditingEntityListener::class)
class Event(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var eventId: Long? = null,

    @OneToOne(
        mappedBy = "event",
        cascade = [CascadeType.ALL],
        orphanRemoval = true,
        fetch = FetchType.LAZY
    )
    var address: EventAddress? = null,

    @CreatedDate
    var createdAt: LocalDateTime? = null,

    @LastModifiedDate
    var updatedAt: LocalDateTime? = null
)
@Entity(name = "event_address")
@EntityListeners(AuditingEntityListener::class)
class EventAddress(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var eventAddressId: Long? = null,

    @OneToOne(fetch = FetchType.LAZY, cascade = [CascadeType.ALL])
    @JoinColumn(name = "event_id")
    var event: Event? = null,

    @CreatedDate
    var createdAt: LocalDateTime? = null,

    @LastModifiedDate
    var updatedAt: LocalDateTime? = null
)

When I insert an Event (which has an address on it), a row is inserted into the Event table, and a row is inserted into the EventAddress table. The problem is in the EventAddress table, the foreign key (event_id) is always NULL.

I'm not sure what I'm doing wrong here.. any help is much appreciated

CodePudding user response:

Does the EventAddress have the event reference set? The foreign key within event_address is controlled by the EventAddress.event property, so if it isn't set, it will be left null - this is a common question/problem with bidirectional relationships; always set both sides as you are responsible for keeping the model in synch with what is in the database. JPA will look at the owning side of the relationship to set foreign keys when they are not in synch.

  • Related