Ryan Lombardo
Ryan Lombardo

Reputation: 333

Getting a child's parent in JDO

I'm running into the issue of the child not having the reference to its parent. Supposedly I've got the setup of a bidirectional relationship where I can get children from the parent and get the parent from the child; however my childrens' parents are always coming back null.

I've got a parent of,

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Company {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent(mappedBy = "company")
    private List<Employee> employees = new ArrayList<Employee>();
}

With a child of,

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Employee {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private Company company;

    @Persistent
    private String username;
}

I'm persisting the object by,

Company newCompany = new Company();
Employee newEmployee = new Employee();
newEmployee.setUsername("ryan");
newCompany.getEmployees().add(newEmployee);
pm.makePersistent(newCompany);

I'm accessing the object like so,

Query query = pm.newQuery(Employee.class,"username == s");
query.declareParameters("String s");
List<Employee> employees = (List<Employee>)query.execute(username);
pm.close();

if (employees.size() > 0)
{
    Employee employee = employeeList.get(0);
    ...
}

I'm then seeing "company" as null when debugging while the rest of the employee's fields are populated. Any thoughts on what I'm missing?

Upvotes: 0

Views: 101

Answers (1)

Neil Stockton
Neil Stockton

Reputation: 11531

Fetching of the parent depends on where you check it, according to the object state. If your PM has been closed by that point then it will not have fetched the parent field. Touching the parent field before closing the PM (and having retainValues set to true, or detaching at close of the PM) will result in the parent field being set.

Upvotes: 1

Related Questions