Identify property of an Object in Java + JPA and change it

2

I am creating a class to get a record of a database and write to another database.

I'm using JPA and I ran into a problem. I'm doing a generic insert and I have to wipe the ID of the table to be able to insert, as it arrives at me a Object I do not know which field to clean and nor how ...

I need two things then, to 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();
    }
}
    
asked by anonymous 23.01.2015 / 17:58

1 answer

3

You can search for the attribute (here represented by the Field class) that has the @Id annotation. Once found, you use the Field.set method of the found attribute itself 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 the set method also requests the instance of the object whose attribute you want to be ( oGet ) in addition to the value you want to ).

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

    
23.01.2015 / 18:09