java - Implementing a Generic Model with basic CRUD operation using ORMlite for Android -


i have abstract classes use base models. sake of simplicity talk root abstract class called model - needs handle repetitive ormlite operation. before each crud operation, needed apply logic standard models. point can implement save, update, , delete on calling object, without having repeat code.

abstract public class model<model extends model, child extends childmodel> {      private final list<child> mchildren = new arraylist<>();     private class<child> mchildclass;     private class<model> mmodelclass;     protected runtimeexceptiondao<model, long> mrtedao;      public model(class<model> modelclass, class<child> childclass) {         this.mchildclass = childclass;         this.mmodelclass = modelclass;         this.mrtedao = app.getopenhelper().getrtedao(this.mmodelclass);     }      // codes omitted...      public void save() {         // object before continuing         mrtedao.create(this);     }      public void delete() {         // object before continuing         mrtedao.delete(this);     }      // codes omitted... } 

the code above gives me error because dao expects sub class "model" instead this refers model<model, child>

the workaround @ moment below:

// codes omitted... abstract protected void handleupdate(); // let subclass handle create/update abstract protected void handledelete(); // let subclass handle delete  public void save() {     // object before continuing     handleupdate(); }  public void delete() {    // object before continuing     handledelete(); } // codes omitted... 

at least reduce code each of model - still doesn't seem elegant. there way me grab "this" object of sub class , not base model class? tried casting, gives me warning unchecked cast.

public void save() {     mrtedao.create((model)this); }  public void delete() {     mrtedao.delete((model)this); } 

this project example has elegant way model class save, update, delete on itself. unfortunately lack features need in ormlite, can't seem ormlite same thing in project because of need generify base model.

ahhh found solution myself :) implement abstract method this:

abstract protected model getthis(); 

here's implementation:

@override protected examplemodel getme() {     return this; } 

then whenever need this behave this of subclass i'm using:

public void save() {     // object before continuing     mrtedao.create(getthis()); }  public void delete() {     // object before continuing     mrtedao.delete(getthis()); } 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -