I have the following entity classes
public class Container {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private final Long id;
@Column(name = "container_id")
private final String containerId;
@OneToMany(cascade = { CascadeType.ALL }, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = ContainerItem.container_id, referencedColumnName = "container_id", nullable = true)
private Collection<ContainerItem> containerItems = Collections.emptyList();
}
public class ContainerItem {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private final Long id;
@Column(name = "container_id")
private String containerId;
@OneToOne(targetEntity = Order.class)
@NonNull
private final Order order;
}
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private final Long id;
@Column(name = "order_id")
private String orderId;
@OneToMany(cascade = { CascadeType.ALL }, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = Product."order_id", referencedColumnName = "order_id")
private Collection<Product> products;
}
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private final Long id;
@Column(name = "order_id")
private String orderId;
@Column(name = "text")
private final String text;
}
I have used random names for objects to keep it simple. (Edited to resemble a fictional real-world scenario to give some meaning to it.
Basically, there are two main operations -
I execute CRUD operations for
Order
andProduct
and there are no issues here. When anOrder
is inserted/updated/deleted, theProduct
is also inserted/updated/deleted.I execute CRUD operations for
Container
andContainerItem
. For this to work successfully, there needs to be someOrder
that can be used by theContainerItem
in its foreign key (OneToOne mapping) that I specified (the column I use for the foreign key is theorderId
inOrder
). I create them too, but I DO NOT want to create/update/delete theOrder
when I insert anContainer
which inserts aContainerItem
containing a mapping to theOrder
. How can I fix this?
At the same time, Order
is not the rightful owner of ContainerItem
and I do not want to have a mapping from the other table.
The save is performed as below with the entityManager
.
public Long create(Container container) {
this.entityManager.persist(container);
this.entityManager.flush();
return container.getId();
}
With the above entity mapping, I see an error as below, which I sort of understand, but do not know how to resolve.
During synchronization a new object was found through a relationship that was not marked cascade PERSIST: Order (id:null, orderId: "1", products: [])
The object received here is correct, I do not want to store/update/delete the state of Order
or Product
. How can I specify this unidirectional relation here?