繁体   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