【问题标题】:Objectify and relations对象化和关系
【发布时间】:2013-11-20 10:40:08
【问题描述】:

我正在尝试实现一个简单的 GAE 服务。特别是我有学生实体和类别实体。每个学生可以关联一个或多个类别。如何使用 Objectify 创建这种关系?谢谢

编辑:这是我的代码。有效吗?

@Entity
public class Studente {
    static long nextID = 17;

    public static Key<Studente> key(long id) {
        return Key.create(Studente.class, id);
    }

    List<Key<Categoria>> categorie; 

    public Studente() {}

    @Id  Long id;
    @Index String nome;
    @Index String cognome;
    @Index String username;
    @Index String password;

    public Studente(String nome, String cognome, String username, String password) {
        this.nome=nome;
        this.cognome=cognome;
        this.username=username;
        this.password=password;
        categorie = new ArrayList<Key<Categoria>>();
    }

    public static long getNextID() {
        return nextID;
    }

    public static void setNextID(long nextID) {
        Studente.nextID = nextID;
    }

    public List<Key<Categoria>> getCategorie() {
        return categorie;
    }

    public void setCategorie(List<Key<Categoria>> categorie) {
        this.categorie = categorie;
    }

    public void addCategoria(Key<Categoria> k ){
        categorie.add(k);
    }
}

【问题讨论】:

    标签: java google-app-engine google-cloud-datastore objectify


    【解决方案1】:

    Student 中创建一个包含所有Category ID(或键)的多值索引字段:

    @Entity
    public class Category {
        @Id
        public Long id;  // auto-generated Id of the Category
    
    }
    
    @Entity
    public class Student {
        @Id
        public Long id;  // auto-generated Id of the Student
    
        @Index
        public List<Long> categories;  // put Category Ids into this list
    }
    

    索引字段可用于查询过滤器,因此您将能够搜索属于某个类别的学生。

    【讨论】:

    • 在回答的同时,我做了一个示例工作代码。你能检查一下我的问题吗?
    【解决方案2】:

    我建议让第三个实体对这两个实体都有索引引用。这样,您就可以轻松地查询某个类别中的每个学生,或每个学生类别。

    @Entity
    public class Student { /*...*/ }
    
    @Entity
    public class Category { /*...*/ }
    
    @Entity
    public class StudentCategory {
        @Id
        private Long id;
    
        @Index
        private Ref<Student> student;
    
        @Index
        private Ref<Category> category;
    
        /*...*/
    }
    

    我们在 GAE 应用程序中有类似的设置,它对我们很有帮助。

    See documentation of Ref&lt;?&gt;.

    【讨论】:

    • 在回答的同时,我做了一个示例工作代码。你能检查一下我的问题吗?
    • 您的解决方案应该可以工作,但不是很方便。 RefKey 更方便(请参阅我链接的文档)。此外,如果您的列表中没有 @Index 注释,您将无法查询具有特定类别的学生。您将只能分辨出不同学生的类别。抛开所有这些,您的解决方案应该可以工作,是的。
    • 您可以在没有中介 StudentCategory 实体的情况下执行相同的操作,方法是使用每个 StudentCategory 中的引用列表。这将为您节省额外的代码和成本。
    • @PeterKnego:那样的话,您将面临数据不一致的风险。学生可以引用该类别,但该类别可能缺少对该学生的引用。如果完全避免这种风险意味着需要额外的代码和成本,我会很乐意接受。
    • @Jan 如我所见,如果代码中的开发人员以某种方式“忘记”更新实体,您的代码也有同样的问题。这可以通过使用经过良好测试的实用函数来创建关系来简单地解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2017-10-05
    • 2015-03-16
    • 2013-05-08
    • 1970-01-01
    相关资源
    最近更新 更多