Matheus Bica Matheus Bica - 25 days ago 4x
Java Question

How to create new Row's without JPA consider it an update?

I'm working in a project right now, here is a piece of code:

public boolean getAll() {
TypedQuery<Tag> query = em.createQuery("SELECT c FROM Tag c WHERE (c.tagName !=?1 AND c.tagName !=?2 AND c.tagName !=?3) ", Tag.class);
query.setParameter(1, "Complete");
query.setParameter(2, "GroupA");
query.setParameter(3, "GroupB");

List<Tag> Tag= query.getResultList();

But when I try to do something like this:

Tag.get(2).setTagName = "Hello";

It considers it to be an update instead of a create? How can I make JPA understand that it's not database related, to detach the chains with the Database and create new register only changing its name for example?

Thanks a lot for any help!
Best regards!


Using the
just before changing it values and persisting each of the list worked just fine!

Thanks everyone!


The decision whether to update or create a new entity object is done based on the primary key. You're probably using an ID on every object. Change or remove it and persist then. This should create a new entry.

If that doesn't work, you might need to detach the object from the Entity Manager first:


and persist it afterwards:


You can also force an update instead of creation by using


There is no equivalent for forced creation AFAIK. persist will do both depending on PK.