Attempt to update registration ID not allowed with JPA and Eclipselink

Asked

Viewed 242 times

4

How do I allow updating the ID of a record with JPA and Eclipselink?

The following exception is thrown when I try to update the ID:

Caused by: Exception [Eclipselink-7251] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.Validationexception Exception Description: The attribute [idnotificacaoTipoEnvio] of class [br.com.ko.Notificacaotipoenvio] is Mapped to a Primary key column in the database. Updates are not allowed.

The attribute is mapped as follows:

@Id
@Basic(optional = false)
@NotNull
@Column(name = "idnotificacao_tipo_envio")
private Integer idnotificacaoTipoEnvio;

The method that does the update is like this:

public void edit(T entity) {
    getEntityManager().getTransaction().begin();
    getEntityManager().merge(entity);
    getEntityManager().getTransaction().commit();
}
  • Could inform the case that gave error, I mean the construction of the object that was edited through the method edit.

1 answer

5


There are two alternatives (I know) for this situation.

Method XGH

  1. Recover the connection object (Connection)
  2. Update via JDBC
  3. Perform a find() to retrieve the new object

Method POG

  1. Perform a remove() to exclude the entity from the EntityManager
  2. Change the ID
  3. Perform a persist() to insert the entity into the bank as if it were a new

Important Considerations

Obviously the above solutions are not ideas. If changing this field is something recurring, then it should not be the table PK.

Another alternative would be to remodel the database with a sequential ID (auto increment) and this field that varies a normal field with a type constraint Unic.

Makes more sense, right?

  • 2

    Actually, about making the ID field as a normal field seems more sensible among the options. Updating is probably not allowed because another table may have a relationship with that ID in question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.