Persisting objects in SugarORM

后端 未结 2 887
一生所求
一生所求 2021-01-28 14:14

I have a Book class:

public class Book extends SugarRecord {
    private String mBookName;
    private String mAuthorName;
    private List mPageList         


        
2条回答
  •  猫巷女王i
    2021-01-28 14:34

    No List available on SugarORM. The way you can manage this is a little tricky. In few words, you can manage 1 to N relations, upside down. Take a look to the next example Lets suppose a Team object which can have N Person objects. Normally you will use a List in your class Team in this way:

    public class Team {
       String teamName;
       List
       ...
    }
    
    public class Person {
       String name;
       String rol;
       ...
    }
    

    Well, it is not possible on SugarORM. But you can add Team as a property in Person, so, any Person's instance should contain a reference to the Team object it belong.

    public class Team extends SugarRecord {
       String teamName;
       ...
    }
    
    public class Person extends SugarRecord {
       String name;
       String rol;
       Team team;
       ...
    }
    

    Then you can get all the Person objects from Team with a method (in the Team class) like:

    public class Team extends SugarRecord {
       String teamName;
       ...
    
        public List getPersons(){
                return Person.find(Person.class, "id = ?", String.valueOf(this.getId()));
        }
    }
    

    So, you can manage 1 to N relations, but you can't manage N to M relationships (Person belonging to more than one Team object). IMO the way to manage this is using an Associative Entity in order to split N to M into two 1 to N relationships. As you can see SugarORM is not allowing you to think just in terms of objects, but, any case you can save a lot of boiler plate coding.

    提交回复
    热议问题