i have a database with 2 tables with a many to many relation.
One table with projects and one with persons. Persons can be in projects or not.
I fill a list with all projects and one with all persons:
Query query = em.createQuery("select p from Project p");
List<Project> projects = query.getResultList();
Query query = em.createQuery("select p from Person p");
List<Person> persons = query.getResultList();
Every person object has a list with the projects the person is in and every project object has a list of all persons in it.
The problem now is that a person in the persons list is a different object as the same person in a project. E.g. if i change the name of a person in the persons list, the person's name isn't changed in the projects which have that person in it cause it's a different object. But shouldn't it be the same one? Or what can i do to make it so it's the same one?
If you are using the same EntityManager, they should be the same instances, as long as they have not been detached/serialized. Can you describe the read process?
If they are detached or different EM instances, the changes need to be merged back into an EntityManager before they will be writen to the database and read by other EMs. You can merge into the one you are reading from or commit the changes back to the first before attempting a read elsewhere.
Thanks for the answer - i am currenty using two EntityManagers. They look like this:
public class ProjectsModel extends MainModel {
public ProjectsModel() throws Exception {
super();
}
public List<Project> readProjects() {
Query query = em.createQuery("select p from Project p");
List<Project> projects = query.getResultList();
return projects;
The PersonsModel looks the same and the MainModel looks like this:
public class MainModel {
protected EntityManager em;
protected EntityTransaction transaction;
public MainModel() throws Exception {
em = EntityManagerFactory.createEntityManager();
transaction = em.getTransaction();
transaction.begin();
}
code for getting the data:
model = new ProjectsModel();
List<Project> projects = model.readProjects();
PersonsModel pm = new PersonsModel();
List<Person> persons = pm.readPersons();
I tried to use one EntityManagaer by making the em and the transaction in the MainModel static and checking if the em exist before making one. The persons then were indeed the same ones, but then i started to get duplicate key errors on different occasions (when changing a persons names 2 times or deleting persons which are in projects) or "Entity must be managed to call remove" when i try to delete persons 2 times. So is using one entitymanager for the 2 model's really a valid or the right solution?