Persisting objects in SugarORM

后端 未结 2 886
一生所求
一生所求 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条回答
  • 2021-01-28 14:33

    No ORM database(SugarORm, DBFLow etc) supports List column. As you know sql don't have this datatype as well.

    That's the reason why you are getting this error. If you ask me how you are saving list to ORM. I use Gson.

    Declare Pagelist as string.

    String Pagelist;

    Before saving it to database convert it to Json string with the help Gson library.

    Gson gson = new Gson();
    String value = gson.toJson(your_page_list);
    

    when retrieving from database convert the json string to List using Gson.

    List<Page> page_list;
      Type typeIndicatorForGson = new TypeToken<ArrayList<Page>>() {}.getType(); 
     Gson myGson = new Gson();  
     page_list = myGson.fromJson(page_json_data_from_database, typeIndicatorForGson); 
    
    0 讨论(0)
  • 2021-01-28 14:34

    No List<Object> 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<Person> in your class Team in this way:

    public class Team {
       String teamName;
       List<Person>
       ...
    }
    
    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<Team> {
       String teamName;
       ...
    }
    
    public class Person extends SugarRecord<Person> {
       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<Team> {
       String teamName;
       ...
    
        public List<Person> 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.

    0 讨论(0)
提交回复
热议问题