0

I always save a Impost before try to save Product.

I can save the Impost, but when I try to save Product (that has Impost) it fails.

My entities are like this:

public class Product {

@Id
@GeneratedValue(strategy = AUTO)
private long id;

@NotNull(message = "Name cant be null")
@Size(min = 1, message = "Name must have at least one char!")
private String name;

@NotNull(message = "Price cant be null")
private Double price;

@NotNull(message = "Type cant be null")
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Impost impost;

}

And the entity for Impost is like this:

public class Impost {

@Id
@GeneratedValue(strategy = AUTO)
private Long id;

@NotNull(message = "The impost has a name!")
@Size(min = 1)
private String name;

@NotNull(message = "The impost percent is not null!")
private BigDecimal percent;
}

This is the request I do to impost:

{
    "name": "impost",
    "percent": "50"
}

This is the request I do to Product:

{
"name": "prod",
"price": "10",
"impost": { "id": 1 }
}

But I always get this error: Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.tax.entity.Impost

1 Answers1

0

The cause if the issue is that you are not using a managed Impost instance when persisting the product.

Set a managed one after you deserialize the product before persisting it:

product.setImpost(entityManager.getReference(product.getImpost().getId()))
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110