引用對象
Mongo在同一個資料庫引用一個文檔(對象)到另一個。考慮一下類:
public class BlogEntry { private String title; private Date publishDate; private String body; private Author author; // getters and setters}...public class Author { private String username; private String fullName; private String emailAddress; // getters and setters} 這裡的一個問題就是:我們如果註解BlogEntry中的author屬性。當然,我們可以是用@Embedded註解,但是這樣就沒什麼意義了,因為在沒個BlogEntry執行個體中都儲存一個Author
對象。我們反而想在多個blog執行個體中引用一個單獨的Author文檔(對象)在Mongo中。
在這種情況下我們使用 @Reference註解
import com.google.code.morphia.annotations.Entity;import com.google.code.morphia.annotations.Embedded;import com.google.code.morphia.annotations.Id;import com.google.code.morphia.annotations.Reference;import com.google.code.morphia.annotations.Property;@Entitypublic class BlogEntry { @Id private ObjectId id; private String title; private Date publishDate; private String body; @Reference private Author author; // getters and setters}...@Entitypublic class Author { @Id private ObjectId id; private String username; private String fullName; private String emailAddress; // getters and setters} 當使用引用時有很重要的一點我們必須提及:被引用的對像在被引用之前必須已經儲存到了MongoDB資料庫中。
這個真的的意思是。就像上面的例子,在你建立一個BlogEntry對象之前,一個Author已經被儲存到了資料庫中。
預設情況下,Morphia使用屬性名稱作為在資料庫中儲存的值。當然這個可以在@Reference註解中指定。
@Reference("blog_authors") private List<Author> authors;
補充:註解使用的參數。
concreteClass: 指定具體的實體類。
ignoreMissing: 忽略任何不能解決的參考。
lazy: 為參考建立一個代理,這個將在第一次調用時載入(類似Hibernate中的lazy屬性)
value: 指定在Mongo中儲存的屬性名稱。
原文串連:http://code.google.com/p/morphia/wiki/ReferenceAnnotation