Unable to persist Json object with Spring Data having @OneToMany relationship

Sunday, July 6, 2014

I have an entity called Sale, which has list of objects SaleData, I have set up unidirectional @OneToMany relationship between these two. Now I ran into a problems when doing CRUD operations on my Sale object.

CascadeType set to ALL.

@Table(name = "sale")
public class Sale extends BaseEntity {

@OneToOne(cascade = CascadeType.DETACH)
private Client client;

@OneToMany(cascade = {CascadeType.ALL}) // <--
@JoinColumn(name = "sale_id", nullable = false)
private List<SaleData> saleData = new ArrayList<>();

Save (POST) and Delete works. What's causing problem is when POST-ing for update, my JSON sent from Angular controller looks like that:

{"id": 1, "client": {
"id": 1,
"firstName": "Test",
"lastName": "Client"
}, "saleData": [
"id": 1,
"employee": {
"id": 1,
"firstName": "Herp",
"lastName": "Derp"
"id": 2,
"employee": {
"id": 1,
"firstName": "John",
"lastName": "Smith"

Update call from Spring service throws:

org.hibernate.PersistentObjectException: detached entity passed to persist: app.sales.SaleData

Service implementation

@Transactional(rollbackFor = SaleNotFoundException.class)
public Sale update(@NotNull SaleDTO updated) {
Sale sale = repository.findOne(updated.getId());

if (sale == null)
throw new SaleNotFoundException("Sale not found");

return transformSaleObject(sale, updated);

As I understand, cascade ALL doesn't make the sale object Deattached, because in 2nd scenario where I replace the type with any combination of...

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH})

.. then Update and Delete works, but Saving a new object does not. I haven't used Hiberate that much, but maybe anyone knows what's causing this behaviour? Is it the matter of defining relationship wrong way?