I want to model One-To-One relationship using Spring Data JDBC and PostgreSQL but I'm having trouble setting up root aggregates the right way.
There's following scenario: Picture, SQL
Each engine is unique, car
has unique column engine_id
which is foreign key of engine.id
, same goes for truck
. Therefore car and truck should be root aggregates so when car or truck is deleted, referenced row from engine table should be deleted as well.
From my understanding of Spring Data JDBC Aggregates
If multiple aggregates reference the same entity, that entity can’t be part of those aggregates referencing it since it only can be part of exactly one aggregate.
So the questions are:
- Is workaround possible due to explanation above so that by performing CRUD operations on
car
andtruck
changes are reflected toengine
as well ? - What's the best way to implement this relationship in java using Spring Data JDBC ?
Here's my take which does not work but should clarify what I'm trying to accomplish.
Car.java
package com.example.dao.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Persistable;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import java.util.UUID;
@Table("car")
public class Car implements Persistable<UUID> {
@Id
private UUID id;
String brand;
String model;
@Column("engine_id")
Engine engine;
public void setId(UUID id) {
this.id = id;
}
@Override
public UUID getId() {
return id;
}
@Override
public boolean isNew() {
return id == null;
}
}
Engine.java
package com.example.dao.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Persistable;
import org.springframework.data.relational.core.mapping.Table;
import java.time.LocalDateTime;
import java.util.UUID;
@Table("engine")
public class Engine implements Persistable<UUID> {
@Id
private UUID id;
String name;
LocalDateTime dateCreated;
String type;
public void setId(UUID id) {
this.id = id;
}
@Override
public UUID getId() {
return id;
}
@Override
public boolean isNew() {
return id == null;
}
}
Truck.java
package com.example.dao.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Persistable;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import java.util.UUID;
@Table("truck")
public class Truck implements Persistable<UUID> {
@Id
private UUID id;
String brand;
String model;
Integer cargoMaxWeight;
String truckType;
@Column("engine_id")
Engine engine;
public void setId(UUID id) {
this.id = id;
}
@Override
public UUID getId() {
return id;
}
@Override
public boolean isNew() {
return id == null;
}
}