Mongodb 的ORM架構 Morphia 註解 之 @Reference

來源:互聯網
上載者:User

  引用對象

     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

          

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.