Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/39122981, this article from "Zhang Hongyang's Blog"
The previous article has made a brief introduction to the Ormlite framework: How to get started with the Android Ormlite Framework ~ ~ This article will describe some of the uses that the project might use, as well as a more reasonable use of our ormlite framework.
Through the previous article, we use ormlite, we need to write a databasehelper to inherit Ormlitesqliteopenhelper, below we first give a I think the more reliable helper of the wording:
1, Databasehelper
Package Com.zhy.zhy_ormlite.db;import Java.sql.sqlexception;import Java.util.hashmap;import java.util.Map;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Com.j256.ormlite.android.apptools.ormlitesqliteopenhelper;import Com.j256.ormlite.dao.dao;import Com.j256.ormlite.support.connectionsource;import Com.j256.ormlite.table.tableutils;import Com.zhy.zhy_ Ormlite.bean.article;import Com.zhy.zhy_ormlite.bean.student;import Com.zhy.zhy_ormlite.bean.user;public Class Databasehelper extends ormlitesqliteopenhelper{private static final String table_name = "sqlite-test.db";p rivate Map <string, dao> Daos = new hashmap<string, dao> ();p rivate databasehelper (context context) {Super (context, TABLE_NAME, NULL, 4);} @Overridepublic void OnCreate (sqlitedatabase database,connectionsource connectionsource) {try{ Tableutils.createtable (Connectionsource, User.class); Tableutils.createtable (Connectionsource, Article.class); Tableutils.createtable (Connectionsource, StuDent.class);} catch (SQLException e) {e.printstacktrace ();}} @Overridepublic void Onupgrade (sqlitedatabase database,connectionsource connectionsource, int oldversion, int NewVersion) {try{tableutils.droptable (Connectionsource, User.class, true); Tableutils.droptable (Connectionsource, Article.class, true); Tableutils.droptable (Connectionsource, Student.class, True); OnCreate (database, connectionsource);} catch (SQLException e) {e.printstacktrace ();}} private static Databasehelper instance;/** * Single case get the helper * * @param context * @return */public static synchronized Databa Sehelper Gethelper (Context context) {context = Context.getapplicationcontext (); if (instance = = null) {synchronized ( Databasehelper.class) {if (instance = = null) instance = new Databasehelper (context);}} return instance;} Public synchronized DAO Getdao (Class clazz) throws Sqlexception{dao dao = null; String className = Clazz.getsimplename (), if (Daos.containskey (className)) {dao = Daos.get (ClassName);} if (dao = = null) {DAO = Super.getdao (cLazz);d aos.put (ClassName, DAO);} return DAO;} /** * Release resource */@Overridepublic void Close () {super.close (); for (String Key:daos.keySet ()) {dao DAO = Daos.get (key);d AO = nul l;}}}
1, the whole databasehelper use a single case only to publish an object, to ensure that there is only one SQLite Connection in the app, reference article: http://www.touchlab.co/2011/10/ single-sqlite-connection/
2, we create a xxxdao for each bean to handle the database operation of the current bean, of course, the object that really goes to deal with the database is obtained by Getdao (T T) in the code above
Getdao is a generic method that creates DAO based on the incoming class object and uses a map to hold all the DAO objects, only the first call to the underlying Getdao ().
2. DAO of Bean
Package Com.zhy.zhy_ormlite.db;import Java.sql.sqlexception;import Android.content.context;import Com.j256.ormlite.dao.dao;import Com.zhy.zhy_ormlite.bean.user;public class Userdao{private Context context;private Dao<user, integer> userdaoope;private databasehelper helper;public Userdao (context context) {This.context = Context;try{helper = Databasehelper.gethelper (context); Userdaoope = Helper.getdao (User.class);} catch (SQLException E ) {e.printstacktrace ();}} /** * Add a user * @param user */public Void Add (user user) {try{userdaoope.create (user)} catch (SQLException e) {e.printstackt Race ();}} ... other operations}
All of our Xxxdao follow the above style ~
Well, basically understand the structure of our code ~~ps: If you feel unreasonable can leave a message to point out, if you feel unable to receive, directly ignore ...
3. Ormlite FOREIGN Key reference
Now we have two sheets, one user, one article;
Article of course need to store the user's primary key, as the association ~ ~ So in ormlite how to do it?
Perhaps someone would declare an int type UserID property directly in the article, as a normal attribute processing, this practice did not do, but did not reflect the object-oriented thinking.
Object-Oriented is this: article belongs to a user
Class is defined like this:
Package Com.zhy.zhy_ormlite.bean;import Com.j256.ormlite.field.databasefield;import com.j256.ormlite.table.DatabaseTable; @DatabaseTable (tableName = "tb_article") public class article{@DatabaseField ( Generatedid = true) private int id; @DatabaseFieldprivate String title; @DatabaseField (Canbenull = true, foreign = true, Colu Mnname = "user_id") private user User;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} Public User GetUser () {return user;} public void SetUser (user user) {this.user = user;} @Overridepublic String toString () {return "article [id=" + ID + ", title=" + title + ", user=" + user+ "]";}}
Does not define a userid of type int, but defines a user member variable directly, indicating that the article belongs to the user;
Then add:@DatabaseField (Canbenull = true, foreign = true, ColumnName = "user_id") on the User user property
Canbenull-Indicates that a foreign key cannot be represented as null;foreign=true; columnName column Name
The user class will temporarily have two properties:
Package Com.zhy.zhy_ormlite.bean;import Com.j256.ormlite.field.databasefield;import com.j256.ormlite.table.DatabaseTable; @DatabaseTable (tableName = "Tb_user") public class User {@DatabaseField ( Generatedid = true) private int id; @DatabaseField (columnName = "name") Private String name;public User () {}public int getId ( ) {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic String toString () {return "User [id=" + ID + ", name=" + name + "]";}}
Now look at our Articledao.
Package Com.zhy.zhy_ormlite.db;import Java.sql.sqlexception;import Java.util.list;import android.content.Context; Import Com.j256.ormlite.dao.dao;import Com.zhy.zhy_ormlite.bean.article;import com.zhy.zhy_ormlite.bean.User; public class Articledao{private Dao<article, integer> articledaoope;private databasehelper helper;@ Suppresswarnings ("unchecked") public Articledao (context context) {Try{helper = Databasehelper.gethelper (context); Articledaoope = Helper.getdao (Article.class);} catch (SQLException e) {e.printstacktrace ();}} /** * Add a article * @param article */public void Add (article article) {try{articledaoope.create (article);} catch (Sqlexcep tion e) {e.printstacktrace ();}} /** * Get a article * @param ID by ID * @return */@SuppressWarnings ("unchecked") public article getarticlewithuser (int id) {ART Icle Article = Null;try{article = Articledaoope.queryforid (ID); Helper.getdao (User.class). Refresh (Article.getuser ()) ;} catch (SQLException e) {e.printstacktrace ();} return article;} /** * Get an article by ID * @Param ID * @return */public article get (int id) {Article article = Null;try{article = Articledaoope.queryforid (ID);} catch (SQLException e) {E.printstacktrace ();} return article;} /** * Get all articles by UserID * @param userid * @return */public list<article> listbyuserid (int userId) {Try{return Articleda Oope.querybuilder (). where (). EQ ("user_id", userId). query ();} catch (SQLException e) {e.printstacktrace ();} return null;}}
Next look at our test class:
public class Ormlitedbtest extends androidtestcase{public void testaddarticle () {User U = new User (); U.setname ("Zhang Hongyang"); new Userdao (GetContext ()). Add (U); Article Article = new article () Article.settitle ("Ormlite use"); Article.setuser (u); new Articledao (GetContext ()). Add ( article);} public void Testgetarticlebyid () {Article Article = new Articledao (GetContext ()). get (1); L.E (Article.getuser () + "," + article.gettitle ());} public void Testgetarticlewithuser () {Article Article = new Articledao (GetContext ()). Getarticlewithuser (1); L.E (Article.getuser () + "," + article.gettitle ());} public void Testlistarticlesbyuserid () {list<article> articles = new Articledao (GetContext ()). Listbyuserid (1); L.E (Articles.tostring ());}
Test separately, add a article; get a article by ID, get a article by ID and carry user; Get all the article through UserID;
See the third: Get a article by ID and carry User,testgetarticlewithuser (ID)
How to value a article ID, and then be able to get the article object, and the internal user property directly assigned value?
Two different ways:
1, that is, the above wording
Article = Articledaoope.queryforid (ID); Helper.getdao (User.class). Refresh (Article.getuser ());
2. On the annotation of the user attribute: @DatabaseField (Canbenull = true, foreign = true, ColumnName = "user_id", Foreignautorefresh = True)
Add Foreignautorefresh =true, so that when the Queryforid is called, the article object is carried directly with the user;
4. Associating a Collection
Each user associates one or more article, if I declare a collection<article> articles in user, can I get the value of articles when I query the user?
The answer is yes. Add the following attributes to the user, and the annotations are as follows:
@ForeignCollectionField
Private collection<article> articles;
We write the code in Userdao that queries the user:
Public User get (int id) {Try{return userdaoope.queryforid (ID);} catch (SQLException e) {e.printstacktrace ();} return null;}
Test code:
public void Testgetuserbyid () {User user = new Userdao (GetContext ()). get (1); L.E (User.getname ()); if (User.getarticles ()! = null) for (article Article:user.getArticles ()) {L.E (article.tostring ()) ;}}
Output:
09-07 22:49:06.484:e/zhy (7293): Zhang Hongyang 09-07 22:49:06.484:e/zhy (7293): article [id=1, Title=ormlite use]
As you can see, we successfully acquired the user, and all the articles associated with the user, through a queryforid;
5, the use of conditional query QueryBuilder
The above code has actually used the simple condition query:
1, the simple where equals
Articledaoope.querybuilder (). where (). EQ ("user_id", userId). query (); return directly to the list of article
2. Where and
Querybuilder<article, integer> QueryBuilder = Articledaoope.querybuilder (); Where<article, integer> where = Querybuilder.where (); Where.eq ("user_id", 1); Where.and (); Where.eq ("name", "XXX" );//or Articledaoope.querybuilder ().//where ().//eq ("user_id", 1). and ().//eq ("name", "xxx");
Both of the above are equivalent to: SELECT * from tb_article where user_id = 1 and name = ' xxx ';
3. More complex queries
Where.or (//where.and (//where.eq ("user_id", 1), Where.eq ("name", "xxx"), Where.and (//where.eq ("user_id", 2), Where.eq ("name", "yyy"));
SELECT * from Tb_article where (user_id = 1 and name = ' xxx ') or (user_id = 2 and name = ' yyy ');
Well, the complexity of the query estimate can also be made up ~ ~
6, Updatebuilder, Deletebuilder
Using QueryBuilder is because we want to perform a complete query to return the List<bean> collection directly;
For update we are not concerned with the return value, directly using
Articledaoope.updateraw (statement, arguments); incoming SQL and Parameters ~ ~
Why in that Articledaoope.updatebuilder (). Updatecolumnvalue ("name", "zzz"). where (). EQ ("user_id", 1); Such a pain.
The same is true for Deletebuilder or the suggestion to directly spell SQL, except, of course, simply to use its api~
7. Transaction operations
Write the following code directly in our DAO:
Transaction Operation Transactionmanager.callintransaction (Helper.getconnectionsource (), new callable<void> () {@ Overridepublic Void Call () throws Exception{return null;});
8. Other operations
1. When the bean inherits basedaoenabled, it can use Bean.create (bean); Bean.update (bean) class operation
For example:
Student extends Basedaoenabled<student, integer>
DAO DAO = Databasehelper.gethelper (GetContext ()). Getdao (Student.class);
Student Student = new Student ();
Student.setdao (DAO);
Student.setname ("Zhang Hongyang");
Student.create ();
The premise DAO needs to be set manually, if DAO is null will error, I feel little use no ...
2. Join
Querybuilder<article, integer> articlebuilder = Articledaoope.querybuilder (); QueryBuilder Userbuilder = Helper.getdao (User.class). QueryBuilder (); Articlebuilder.join (UserBuilder);
Article and user do join operation;
This article mainly wants to introduce in the project how to write Databasehelper already how to write the Beandao, as well as lists in the project may use the Ormlite function, if needs the detailed understanding, also please see Ormlite Official document, the source also will provide ~ ~
SOURCE Click to download
The use of the Android Rapid Development Series Ormlite Framework