Question

First of all, as you can see, I work in Java and specifically in NetBeans IDE. So, I have a class Person that extends two classes : Trainer, and Athlete.

In the main, I create a new ArrayList list = new ArrayList();

and then, i fill the list with objects that I've created and made persistent.

Trainer tr1=        new Trainer("George","White","England",5665);
Athlete ath1=       new Athlete("Mairy","Willians","France",1,'f',"21/3/1988",68,172,"France");
list.add(ath1);
Athlete ath2=new Athlete("Iggy","Black","USA",2,'f',"10/4/1988",70,175,"U.S.A.");
list.add(ath2);
tr1.setAthletes(list);

(Those fields, are well defined in the constructor of the classes trainer, and athlete respectively.

I also make them persistent.

em2.persist(tr1);
em2.persist(ath1);
em2.persist(ath2);

But in the end, despite of Athletes and Trainers being persistent, the lists that I have are not.

Thats where my problem starts, I want those lists to be persistent.

Here, those lists are working and tested and there are ok, but they are good to go in Java level, and not in ObjectDB level.

Should i start over?

Anyone that can help me out with this guys? I really need help, that's serious.

PS: Of course, I have made the imports that are needed such as

import javax.persistence.*;
import java.util.*;

EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("$objectdb/db/personas2.odb");
EntityManager em2 = emf2.createEntityManager();
em2.getTransaction().begin();
em2.close();
emf2.close();
Was it helpful?

Solution

But in the end, despite of Athletes and Trainers being persistent, the lists that I have are not.

Some ideas:

  • Make sure that you commit the transaction (although you mentioned that entities are persisted).

  • If your one to many association between Trainer and Athlete is bi-directional (maybe show your entities), make sure to set the "other" side of the link correctly, like this:

    Trainer tr1 = new Trainer("George","White","England",5665);
    Athlete ath1 = new Athlete("Mairy","Willians","France",1,'f',"21/3/1988",68,172,"France");
    ath1.setTrainer(tr1); // set the other side of the link
    list.add(ath1);
    ...
    tr1.setAthletes(list);
    

    or add a method in your entity (in Trainer here):

    public void addToAthletes(Athlete athlete) {
        athlete.setTrainer(this);
        this.athletes.add(athlete);
    }
    

    and replace the above lines with:

    Trainer tr1 = new Trainer("George","White","England",5665);
    Athlete ath1 = new Athlete("Mairy","Willians","France",1,'f',"21/3/1988",68,172,"France");
    tr1.addToAthletes(ath1);
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top