中的另一個實體我在Objectify中遇到與實體關係有關的問題。我的應用程序是一個事件應用程序,其中事件具有不同類別每張票都由用戶擁有。我有一個父/子層次結構,例如Event> TicketType> Ticket。所以,Event是TicketType的@Parent,它是Ticket的@Parent。無法將從交易中獲得的實體關聯到Objectify
這裏是我的實體:
@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);
我在做:
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");
}
我的問題是父/子關係似乎只能在正確擁有所有事件/ TicketTypes(通過ticketTypes
場,這是一個Set<Ref<TicketType>>
的列表Event
實體受到尊重。但是,TicketType
實體沒有票證列表(tickets
字段爲空,因此未保存),而在另一方向上,Ticket
中的父引用爲空,因此TicketType
中的父引用爲Event
,儘管存在我在上述兩種情況下都做了任務。
我該怎麼做?
感謝您的回覆。我在文檔中看到@Load註釋也適用於實體集合,這意味着票據類型應該用Event實體加載。我理解錯了嗎?此外,爲什麼我將TicketType創建爲實體是因爲票證的類型有很多屬性,並且可能有與之相關的行爲(有多少可用?,價格,折扣政策等)。你能給我一個特定的代碼示例嗎? – sbruno74