I have an existing java application in which I use now spring-boot and data jpa to save some data in a database. In one class Order
which I convert now to an @Entity
I have a member which is a List<Position>
. Following is the code of the reduced classes
@Entity
public class Order
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private List<Position> positions;
//some other members follow here...
}
@Entity
public class Position
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
//some members follow here...
}
So what I have done is the following, I added the annotation @Transient
to my list in Order
and add inPosition
a reference to an Order:
@Entity
public class Order
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Transient
private List<Position> positions;
//some other members follow here...
}
@Entity
public class Position
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@ManyToOne
private Order order;
//some members follow here...
}
Now when I want to save an Order object, then I save first the Order in the corresponding repository and then go through the list of Positions and set in ervery the reference to Order and then save the Position object to its corresponding repository. If I want to fetch an Order then I fetch first the Order and then fetch the Positions in the correspoding repository with findByOrder(..)
.
So far this works. Now I'm facing the problem, if the application modifies in the Order the list with the Positions and I have to update the database with the new Order object, then I find no smooth solution to delete the Positions in the repository which were removed from the list by the application (as I have no longer a reference to the removed ones). I could delete first all Positions of that Order and then save the existing ones again.
So my questions is maybe if there is a better way to remove the Positions in the repository which were removed by the application. But maybe it would be an XY question, cause my approach how to save the Position-List is the reason why I am facing this problem. I appreciate any hints concering this.