Search code examples
javajpaeclipselink

JPA merge of a @OneToOne entity relationship


I have a @OneToOne relationship between two JPA entities, the following example is simplified and not the real entity names.

@Entity
public class Stock {

    @Id
    private Long id;

    @OneToOne(fetch = FetchType.Lazy, mappedBy = "stock", cascade = CascadeType.ALL)
    private StockDetail detail;

}

And StockDetail

@Entity
public class StockDetail {

    @Id
    private Long id;

    @OneToOne
    @JoinColumn(name = "STOCK_ID")
    private Stock stock;
}

In my example I need to search for stock by ID and then update the stock detail using merge eg.

Stock stock = em.find(Stock.class, 1L);
StockDetail detail = stock.getDetail();
// Do some updates to detail
detail = em.merge(detail);

At this point with the debugger I can see that the returned detail from the merge is the updated JPA entity. However I have an issue when I do the following again.

Stock stock = em.find(Stock.class, 1L);
StockDetail detail = stock.getDetail();

detail now seems to have the old state of the entity, I'm not sure what's wrong with the above


Solution

  • This was actually a combination of @NicoVanBelle and @janith1024 comments.

    1. There were two entitymanagers, a non-cached em used to do the find and a cached em used for doing the merge.
    2. Once I made the non-cached em do the merge on the stock, it started working.