簡體   English   中英

在Android Studio上使用Android和Google App Engine

[英]Using Android & Google App Engine on Android Studio

我正在開發具有后端的應用程序,因此決定嘗試將Google App Engine用於后端。 由於我真的是Google App Engine的新手,因此我對邏輯有點困惑。

基本上,我有幾個模型類來表示我的對象類型。 可以說其中一個是User,另一個是Item。 用戶擁有項目,並且一個項目可以屬於多個用戶。 因此,用戶X可以有25個項目,包括項目A,而用戶Y可以有完全不同的20個項目,還有項目A。

現在,我的User類看起來像這樣:

@Entity
public class User {

    @Id private Long id;
    private String name;
    private String emailAddress;
    private String photoURL;

    //All getters and setters...
}

我的Item類大致相同。 我的問題之一是,應該在哪里添加某種列表,例如“用戶”中的“項目”列表。 我應該使用哪個注釋? 該注釋將為我提供什么結果(引用,ID或完整對象)?

與此相關的另一個問題是,在端點類中,如何獲得特定用戶擁有的項目列表(或擁有特定項目的用戶列表)?

最后一個完全不相關的問題,如果插入項目時不提供任何ID,我應該做些什么使id自動增加?

您可以在數據存儲區中搜索兩件事:鍵和索引屬性。

class Thing {
   @Id Long id;
   @Index String property;
}

在某個時候,您保存了一些實體

Thing thing1 = new Thing();
thing1.property = "yes";
Thing thing2 = new Thing();
thing2.property = "no";
ofy().save().entities(thing1, thing2).now();

現在,您可以根據其索引屬性搜索所有實體。 例如,所有具有property == "yes"事物。

List<Thing> things = ofy().load().type(Thing.class).filter("property", "yes").list();

將完全返回thing1

屬性列表也是如此。 它與其他屬性的引用/鍵列表一起使用。

class User {
    @Id Long id;
    @Index List<Key<Item>> items;
}

class Item {
    @Id
    Long id;
}

List<User> searchUsersWithItem(long itemId) {
    Key<Item> itemKey = Key.create(Item.class, itemId);
    return ofy().load().type(User.class).filter("items", itemKey).list();
}
List<User> searchUsersWithItem(Item item) {
    return ofy().load().type(User.class).filter("items", item).list();
}
// just loads all the referenced items in the owner
List<Item> searchItemsWithOwner(User owner) {
    return new ArrayList<Item>(ofy().load().<Item>values(owner.items).values());
}

filter可用於ref,鍵和實體實例。

被發現的東西必須被索引https://cloud.google.com/datastore/docs/concepts/indexes / https://github.com/objectify/objectify/wiki/Queries

您需要決定的是如何建立關系模型。 有多種方法。 擁有可以由一組用戶擁有的一組項目的用戶實際上是多對多關系。 你可以像這樣代表它

class User { List<Key<Item>> items; }
class Item { }

要么

class User { }
class Item { List<Key<User>> owners; }

要么

class User { List<Key<Item>> items; }
class Item { List<Key<User>> owners; }

甚至

class User { }
class Item { }
class Ownership { Key<Item> item; Key<User> user; }

每種方法在數據一致性和可搜索性/性能方面都有起有落。 在最初的示例中,搜索用戶的所有項目很簡單,因為您要做的就是加載一個用戶,並且您擁有項目列表。 另一個方向需要查詢方法。

因此,就搜索性能而言,您將受益於項目中的所有者列表以及用戶中的項目列表,因為那樣您根本就不需要查詢。 最大的缺點是數據一致性。 如果您無法同時更新用戶和項目,則可以在用戶認為與眾不同的地方擁有被認為歸用戶所有的項目。

最后一種使用顯式“所有權”實體的方法實質上是傳統的數據透視表/聯結表https://en.wikipedia.org/wiki/Many-to-many_%28data_model%29 ,這是轉換多對多的結果關系分為2個一對多關系。 使用它會導致容易的一致性,但是查詢性能最差。

父母關系有時可能有用,但前提是必須存在實際的一對多關系。

還要注意,鍵如何不像傳統SQL數據庫那樣是外鍵,因為它們可以不存在實體而存在。 因此,無論您做什么,都必須保持一致性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM