Updating collection of dependent objects
I have a class Event and a dependent class Entry, which instances are only valid in the context of an event.
What would be the best way to model this in JDO? Acutally I don't want to query for Entries only for Events and their entries. So do I need a key on Entry?
My current solution is:
@PersistenceCapable
public class Event {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public Long id;
@Persistent
public List<Entry> entries = new ArrayList<Entry>();
}
@PersistenceCapable
public class Entry {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public Key key;
@Persistent
public String name;
}
I tried to add an entry to an existing Event, but it doesn't acutally persist the changed Event:
Event e = null;
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
e = pm.getObjectById(Event.class, Long.parseLong(id));
System.out.println(e.entries.size());
Entry entry = new Entry();
entry.name = name开发者_运维技巧;
e.entries.add(entry);
pm.makePersistent(e);
System.out.println(e.entries.size());
} catch (NumberFormatException nfe) {
return null;
} finally {
pm.close();
}
return e;
I tried to make Entry an Embedded entity, but it is not allowed to have collections of embedded objects.
Actually updating was not the problem. I did not load the event properly in my service.
public Event loadEvent(String id) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Event event = pm.getObjectById(Event.class, Long.parseLong(id));
// And load entries
for (Entry entry : event.getEntries()) {
entry.amounts.size();
}
return event;
} catch (NumberFormatException e) {
return null;
} finally {
pm.close();
}
}
After adding adding the lines between the comment and the return statement all entries were shown properly.
精彩评论