Persisting objects in SugarORM

◇◆丶佛笑我妖孽 提交于 2019-12-02 08:46:26

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); 

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!