Data JPA - Remove entities from repository
<p>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 <code>Order</code> which I convert now to an <code>@Entity</code> I have a member which is a <code>List&lt;Position&gt;</code>. Following is the code of the reduced classes</p>

<pre><code>@Entity
public class Order
{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    private List&lt;Position&gt; positions;

    //some other members follow here...
}

@Entity
public class Position
{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    //some members follow here...
}
</code></pre>

<p>So what I have done is the following, I added the annotation <code>@Transient</code> to my list in <code>Order</code> and add in<code>Position</code> a reference to an Order:</p>

<pre><code>@Entity
public class Order
{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    @Transient
    private List&lt;Position&gt; 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...
}
</code></pre>

<p>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 <code>findByOrder(..)</code>.</p>

<p>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.</p>

<p>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.</p>