Change of entity reflect on related entities

Asked

Viewed 99 times

0

I have two entities, for example:

Note: Fictional code to facilitate understanding of the problem.

@Entity
public class Celular{
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    private String modelo;
    @OneToMany(mappedBy = "celular")
    private List<chamada> chamadas;
}

@Entity
public class Chamada{
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    @ManyToOne
    @JoinColumn(name = "idcelular")
    private Celular celular;
}

It happens that when changing the attribute of the Cellular object, it is not reflected in the Call object. Example:

...
Chamada ch=celular.getChamada().get(0);
System.out.println(ch.getCelular().getModelo()); //imprime "NOKIA"

celular.setModelo("Motorola");

//persistir
getEntityManager().getTransaction().begin();
celular = getEntityManager().merge(entity);
getEntityManager().getTransaction().commit();
getEntityManager().close();

Chamada ch=celular.getChamada().get(0);
System.out.println(celular.getModelo()); //imprime "Motorola"
System.out.println(ch.getCelular().getModelo()); //imprime "Nokia"

What would be the correct procedure for the object chamada notice the change in celular?

  • Your problem should be time to save the relationship. You should always do a.setB(b) and b.set(A). Be sure to perform the relationships correctly before persisting in DB.

1 answer

1

Try to do entityManager.refresh(cellular);

Refresh the state of the instance from the database, overwriting changes made to the Entity, if any.

  • It would be the same as making a cell phone=getEntityManager(). find(Celular.class, celular.getId()); ?

  • refresh receives an entity and updates its attributes with the database data (suppose another concurrent transaction has committed, and you want to make sure you have the data updated). find, from a Primary key, retrieves an entity from the persistent context, which can happen here, depending on its configuration, entitymanager will not necessarily descend into the direct database (It can take some previously obtained reference [if any other transaction has made changes to the data, the one in memory will not see the changes]).

  • Reference links to the above methods: find: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#find(java.lang.Class, java.lang.Object) refresh: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#refresh(java.lang.Object)

Browser other questions tagged

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