I had successfully written my first master child example with hibernate. After few days I took it again and upgraded some libraries. No sure what did I do but I could never
Here you have used native and assigning value to the primary key, in native primary key is auto generated.
Hence the issue is coming.
For JPA fixed using EntityManager merge() instead of persist()
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
em.merge(fieldValue);
em.getTransaction().commit();
} catch (Exception e) {
//do smthng
} finally {
em.close();
}
You didn't provide many relevant details so I will guess that you called getInvoice
and then you used result object to set some values and call save
with assumption that your object changes will be saved.
However, persist
operation is intended for brand new transient objects and it fails if id is already assigned. In your case you probably want to call saveOrUpdate
instead of persist
.
You can find some discussion and references here "detached entity passed to persist error" with JPA/EJB code
I had the "same" problem because I was writting
@GeneratedValue(strategy = GenerationType.IDENTITY)
I deleted that line due that I do not need it at the moment, I was testing with objects and so. I think it is <generator class="native" />
in your case
I do not have any controller and my API is not being accessed, it is only for testing (at the moment).
This exists in @ManyToOne relation. I solved this issue by just using CascadeType.MERGE instead of CascadeType.PERSIST or CascadeType.ALL. Hope it helps you.
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;
Solution:
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;
Most likely the problem lies outside the code you are showing us here. You are trying to update an object that is not associated with the current session. If it is not the Invoice, then maybe it is an InvoiceItem that has already been persisted, obtained from the db, kept alive in some sort of session and then you try to persist it on a new session. This is not possible. As a general rule, never keep your persisted objects alive across sessions.
The solution will ie in obtaining the whole object graph from the same session you are trying to persist it with. In a web environment this would mean:
If you keep having issues post some of the code that is calling your service.