Android-ORM


Source link: https://github.com/Jamling/Android-ORM

Introduction

Did you used sqlite to save your data on Android? If you did, you may be puzzled for the complexity of mechanism. Now the Andoird ORM (Aorm) coming which armed to make it simple for the developers. If you have the interesting, please join us.

Features

  • Brief ORM mapping, just write an annotation for the field of Java beans. e.g. @Column(name="_name") to mapping _name columnn of database to name property.
  • Powerful Forward Engineering supporting, generating DDL and ContentProvider automaticlly.
  • Useful Assist feature, create your Activity/Service/BroadcastReceiver with a wizard and configurat them in AndroidManifest.xml automatically.
  • ... More feature, please experience it for your self.

Usage

The $latest is: , please replace the $latest to a concrete version.

Use in Eclipse

Put aorm-core- $latest.jar to libs/

Recommended to install Android ADT-extensions plugin, and add ORM capapility to enable Aorm.

Use in Android Studio

Aorm has been published to jcenter, so you can just add dependence of aorm in your build.gradle.

dependencies {

  compile 'cn.ieclipse.aorm:aorm-core:1.1.5' 
}

Recommended to install Android ORM Tool plugin to generate code quickly.

Comparision Results

These are the results for the Simple trial:

And these are the results for the Complex trial:

More detail please see https://github.com/Raizlabs/AndroidDatabaseLibraryComparison

Code samples

Create mapping

Simply add @Table class annotation and @Column field annotation to mapping.

@Table(name = "student") public class Student implements Serializable {

 @Column(name = "_id", id = true)
  public long id; //id is Primary key.

 @Column(name="_name")
  public String name; //mapping to _name and auto column type

 @Column()
  public int age; //auto column type and name

 @Column(defaultValue="''")
  public String phone; // default value in empty

 public String address; // no mapping 
}

Create database

package cn.ieclipse.aorm.example;  import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import cn.ieclipse.aorm.Aorm; import cn.ieclipse.aorm.Session; import cn.ieclipse.aorm.example.bean.Course; import cn.ieclipse.aorm.example.bean.Grade; import cn.ieclipse.aorm.example.bean.Student;  /**  * @author Jamling  *   */ public class ExampleContentProvider extends ContentProvider {

 public static final String AUTH = "cn.ieclipse.aorm.example.provider";
  public static final Uri URI = Uri.parse("content://" + AUTH);

  private SQLiteOpenHelper mOpenHelper;
  private static Session session;

 @Override
  public int delete(Uri arg0, String arg1, String[] arg2) {

return 0;
  
}

 @Override
  public String getType(Uri arg0) {

return null;
  
}

 @Override
  public Uri insert(Uri arg0, ContentValues arg1) {

return null;
  
}

 @Override
  public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,

 String arg4) {

return null;
  
}

 @Override
  public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {

return 0;
  
}

 public static Session getSession() {

return session;
  
}

 @Override
  public boolean onCreate() {

mOpenHelper = new SQLiteOpenHelper(this.getContext(), "example.db",

  null, 1) {

 public void onCreate(SQLiteDatabase db) {

  // method 3: use AORM to create table

  Aorm.createTable(db, Grade.class);

  Aorm.createTable(db, Student.class);

  Aorm.createTable(db, Course.class);

 
}

  public void onUpgrade(SQLiteDatabase db, int oldVersion,

int newVersion) {

  // update table, suggested to wrapper in if block

  Aorm.updateTable(db, Grade.class);

  Aorm.updateTable(db, Student.class);

  Aorm.updateTable(db, Course.class);

 
}

}
;

session = new Session(mOpenHelper, getContext().getContentResolver());

return true;
  
}

}

Query

Session session = ExampleContentProvider.getSession();
 // simplest query, query all student table. Criteria criteria = Criteria.create(Student.class);
 // add restrication: id equals criteria.add(Restrictions.eq("id", 1));
 // add restriction: name like Jamling criteria.add(Restrictions.like("name", "Jaming"));
 // add restriction: age < 30 criteria.add(Restrictions.lt("age", 30));
 // add order criteria.addOrder(Order.asc("age"));
 // set district criteria.setDistinct(true);
 // set limit from row 10 to 20 criteria.setLimit(10, 10);
  List<Student> list = session.list(Student.class);
 // if you use Android CursorAdapter you can: Cursor c = session.query(criteria);
  // set alias, so the project will be alias.columnn. e.g. s.name // criteria.setAlias("s");
 // multi-table query criteria.addChild(StudentMore.class, "m", Criteria.INNER_JOIN,

Restrictions.geProperty("s.id", "m.id"));
 // query to cursor c = session.query(criteria);
 // convert to list. List<Object[]> ret = CursorUtils.getFromCursor(c,

new Class[] {
 Student.class 
}
, new String[] {
 "s", "m" 
}
);
 // query to list. ret = session.listAll(criteria);
 Object[] item = ret.get(0);
 Student s = (Student) item[0]; StudentMore m = (StudentMore) item[1]; //

Other

Session session = ExampleContentProvider.getSession();
 // insert Student s = new Student();
 s.setName("Jamling");
 long rowId = session.insert(s, null);
 // update student's name to Jame whose id is 1 s.setId(1);
 s.setName("Jame");
 int rows = session.update(s);
 // delete student whose id is 2 session.deleteById(Student.class, 2);
 // query student whose id is 4 s = session.get(Student.class, 4);

Docs

Refer: http://www.ieclipse.cn/p/Android-ORM/userguide.html

Author

Jamling Jamling ( [email protected])

Resources

Dynamic iOS-like blur of underlying Views for Android.

This is a simple Rx Event Bus implementation using Kotlin.

Code beautifier for Android - a wrapper around a WebView running HighlightJS.

That image ViewPager you have to code for every Android project - use this instead.

Android UI library that creates 'chip' clouds.

Map tools for Android.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes