views:

31

answers:

1

Let's say I have a class Employee and a class Company which holds a LinkedList of Employee objects, and I want to write a method that adds an Employee to the database in a specific Company. I create a new Company object and add it to the database with the new Employee if the Company does not already exit. Else, I add the new Employee to the specified Company's LinkedList<Employee> employee.

My question is, do I need to make the new Employee persistent before adding it to the LinkedList, which is in itself persistent? Or can I just say something like:

 public void addEmployeeToCompany(Employee employee, companyName) {
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
        Company company = pm.getObjectById(Company.class.getSimpleName(), companyName);
        if(company != null) { 
            company.addEmployee(employee);
        }
        else { 
            Company newCompany = new Company(companyName, employee);
            Key key = KeyFactory.createKey(Company.class.getSimpleName(), companyName);
            newCompany.setKey(key);
        pm.makePersistent(newCompany);
        } 
    } 
}

Thank you.

+1  A: 

Yes, persisting only company should persist employees as well. But the real question is what annotations do your company and employee classes have? Also, do you have any specific problem with this, that is, why are you asking - are you getting an exception?

Domchi
Both Employee and Company are marked @PersistenceCapable. I'm not having any specific problems. I am in the midst of learning about databases and was just wondering. Thank you!
ayanonagon
I think all I am missing is pm.makePersistent(venue) after company.addEmployee(employee).
ayanonagon