我对 Objectify 中的实体关系有一些问题。我的应用程序是一个事件应用程序,其中事件具有不同类别的门票;每张票都归一个用户所有。我有一个父/子层次结构,例如 Event > TicketType > Ticket。因此,Event 是 TicketType 的 @Parent,即 Ticket 的 @Parent。
这是我的实体:
@Entity
public class Event {
...
@Load
private Set<Ref<TicketType>> ticketTypes = new HashSet<Ref<TicketType>>();
...
}
@Entity
public class TicketType {
...
@Parent
private Ref<Event> event;
...
}
@Entity
public class Ticket {
...
@Parent
@Load
private Ref<TicketType> ticketType;
...
}
我在这样的事务中创建事件:
Event ev = ofy().transact(new Work<Event>() {
@Override
public Event run() {
// several statements constructing the event
ev.setXXXX(X);
ofy().save().entity(ev).now();
// Now construct the TicketType entity, then associate it to its parent, Event
TicketType tt1 = new TicketType("normal", 100, 7);
tt1.setEvent(ev);
ofy().save().entity(tt1).now();
return ev;
}
});
使用返回的ev
,我像这样创建票证:
// Generate a VIP ticket
Ticket ticket1 = ev.generateTicket("vip");
// I set the owner with an already saved User entity
ticket1.setOwner(cl);
ofy().save().entity(ticket1).now();
// The user also has a list of all his tickets
cl.addTicket(ticket1);
在 Event.generateTicket(...) 中,我这样做:
public synchronized Ticket generateTicket(String type) throws IllegalArgumentException {
for (Ref<TicketType> reftt : ticketTypes) {
TicketType tt = reftt.get();
if (tt.getType().equalsIgnoreCase(type)) {
if (tt.getAvailable() > 0) {
Ticket newTicket = new Ticket(RandomGenerator.nextNumber(TICKET_NUMBER_LENGTH), tt);
newTicket.setExpirationDate(getEndDate());
// here I set the parent TicketType entity for this new Ticket
newTicket.setTicketType(tt);
// the number of available tickets of this type is decreased
tt.setAvailable(tt.getAvailable() - 1);
return newTicket;
} else return null;
}
}
throw new IllegalArgumentException("No such type");
}
我的问题是,父/子关系似乎只在Event
正确具有所有事件/票证类型列表的实体上受到尊重(通过ticketTypes
字段,这是一个Set<Ref<TicketType>>
。但是,该TicketType
实体没有票证列表(该tickets
字段为空,因此未保存),而在另一个方向上,中的TicketType
父引用Ticket
为空,中的Event
父引用也为空TicketType
,尽管我在上述两种情况下都进行了分配。
我做错了什么?