chennaione / sugar

Insanely easy way to work with Android Database.
http://satyan.github.com/sugar/
MIT License
2.62k stars 583 forks source link

How to Use Composite Design Pattern with Sugar ORM #414

Open HosseinKurd opened 9 years ago

HosseinKurd commented 9 years ago

Hi As we know, we need to make our projects According to Design Patterns Standards. So How to use Composite Design Pattern with Sugar ORM The link below Explain it https://en.wikipedia.org/wiki/Composite_pattern

colabug commented 8 years ago

Looks like you have to save each item separately: https://github.com/satyan/sugar/issues/443

That said, not sure how complex the object can be/how deeply nested.

sibelius commented 8 years ago

@HosseinKurd could you please explain more about it?

HosseinKurd commented 8 years ago

@sibeliusseraphini Please use Composite pattern and whatch output in logca https://en.wikipedia.org/wiki/Composite_pattern

sibelius commented 8 years ago

@HosseinKurd could you please provide an example code or gist?

kassisdion commented 8 years ago

I'm facing the same problem so I use my own fk but it prevent from using SugarOrm.saveInTx() and make applications slower (because it now commit on every insertion).

public class Monster extends SugarRecord {
    @Expose
    @SerializedName("id")
    @Unique
    public int monster_id;// the sql table will be called monsterid (see sugarOrm doc)

    @Expose
    public String hp;

    @Expose
    public int defense;

    @Expose
    public int attack;

    @Expose
    public String name;

    @Expose
    public String sprite;
}
public class UserMonster extends SugarRecord {
    @Expose
    public Monster infos;

    @Expose
    public String level;

    @Expose
    public String surname;

    @Expose
    public String experience;

    public int fkmonster;//key for Monster<->UserMonster relationship
}
public void updateUserMonster(Response<UserMonsterResponse> response) {
    UserMonster.deleteAll(UserMonster.class);

    /*
    ** Since every 'Monster' were already saved, no need to call userMonster.info.save()
    ** Since calling Monster.saveInTx(response.body().monsters); cause
    **  Select.from(UserMonster.class).list().get(0).infos = null; to be null
    ** we manage our own fk
    */
    for (UserMonster userMonster : response.body().monsters) {
        userMonster.fkmonster = userMonster.infos.monster_id;
        userMonster.save();
    }
}