Identify an Object property in Java+JPA and change it

Asked

Viewed 177 times

2

I’m creating a class to get a database record and write to another database.

I’m using JPA and bumped into a problem. I’m doing a generic insertion and I have to clean up the ID of the table to be able to insert, as enough for me a Object I don’t know which field to clear and how...

I need two things then, identify which class property is @Id and how to clean it.

In the code below I put a comment aqui showing where the unknown is.

class InsertObject implements Runnable {

    private final int integrationId;
    private final Class entityClass;
    private final EntityManager emOrigem;
    private final EntityManager emDestino;

    public InsertObject(int integrationId, Class entityClass, EntityManager emOrigem, EntityManager emDestino) {
        this.integrationId = integrationId;
        this.entityClass = entityClass;
        this.emOrigem = emOrigem;
        this.emDestino = emDestino;
    }

    @Override
    public void run() {
        // carrega objeto origem
        String sql = "SELECT x FROM " + entityClass.getSimpleName() + " x WHERE integracaoId = " + integrationId;
        Query qOrigem = emOrigem.createQuery(sql);
        Object oOrigem = qOrigem.getSingleResult();

        // remove id
        emOrigem.detach(oOrigem);
        //oOrigem.setId(null); // <<<< AQUI <<<<<<<<<

        // salva no destino
        emDestino.getTransaction().begin();
        emDestino.persist(oOrigem);
        emDestino.getTransaction().commit();
    }
}

1 answer

3


You can search for the attribute (here represented by the class Field) which has the annotation @Id. Once found, you use the method Field set. of the attribute itself found to set its value to null.

for (Field atributo: oOrigem.getClass().getDeclaredFields()) {
    Id anotacaoId = atributo.getAnnotation(Id.class);
    if (anotacaoId != null) {
        atributo.setAccessible(true);
        atributo.set(oOrigem, null);
    }    
}    

Note that the object found is an instance of a class metadata, not a reference to the object attribute itself. So that method set also asks the instance of the object whose attribute you want to set (theOrigem) beyond the value you want to set (null).

The annotation @Id when assigned to a class field, usually this field is private or protected. That’s why I used the method setAccessible is to make it accessible; otherwise an inaccessible member exception would occur.

Browser other questions tagged

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