【问题标题】:how to create a model for nested maps in java?如何在java中为嵌套地图创建模型?
【发布时间】:2021-08-06 14:06:58
【问题描述】:

我正在我的 Android 应用中使用 Firestore,并且我正在使用模型来处理 Firestore 中的数据。但我想减少对小数据集的 Firestore 读取。在网上搜索后,我发现 Firestore 中的嵌套地图是减少小型数据集读取的更好方法。

但问题是如何为嵌套地图创建模型(有时也需要嵌套 4 次)? 下面是一些我想如何创建嵌套地图的示例代码。

    String[] backlogs = {"subject1", "subject2", "subject3"};
    List<String> logs = Arrays.asList(backlogs);
    
    Map<String, Object> student = new HashMap<>();
    student.put("name", STUDENT_NAME);
    student.put("id", STUDENT_ID);
    student.put("backlogs", logs);

    Map<String, Object> sectionA = new HashMap<>();
    sectionA.put("students", student);

    Map<String, Object> college = new HashMap<>();
    college.put("sections", sectionA);

请有任何建议..

【问题讨论】:

  • 如果您正在执行大量的小型读取和写入操作,请考虑使用 Firebase 的实时数据库,因为它可能更具成本效益。
  • @FrankvanPuffelen 但是数据不会经常变化。现在我想将许多小数据集与嵌套地图合并。如果你知道如何设计一个模型类,请写一个答案。

标签: java android firebase google-cloud-firestore


【解决方案1】:

以前我也为此苦苦挣扎。经过多次尝试,我找到了这个解决方案。试试这个来获取嵌套地图。

public class College {
    String name;
    Section section;


    public College() {
    }

    public College(String name, Section section) {
        this.name = name;
        this.section = section;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Section getSection() {
        return section;
    }

    public void setSection(Section section) {
        this.section = section;
    }

    static class Section{
        String Section;
        Student student;

        public Section() {
        }

        public Section(String section, Student student) {
            Section = section;
            this.student = student;
        }

        public String getSection() {
            return Section;
        }

        public void setSection(String section) {
            Section = section;
        }

        public Student getStudent() {
            return student;
        }

        public void setStudent(Student student) {
            this.student = student;
        }
    }

    static class Student{
        String name;
        String id;

        public Student() {
        }

        public Student(String name, String id) {
            this.name = name;
            this.id = id;
        }


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }
    }

我想这就是你需要的。

这将为您提供嵌套地图。如果需要,更改上面的代码以添加列表。

【讨论】:

    猜你喜欢
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多