ORMLite完全解析(一)

   在android中使用原始的SQLiteOpenHelper操作数据库显得过于繁琐,而且对于不是很熟悉数据库操作的人来说比较容易出现一些隐藏的漏洞。所以一般都会想到使用相关的ORMLite框架完成开发,类似于J2EE开发中的Hibernate和Mybatis等等,在提高开发效率的同时,也可以有效避免数据库操作对应用带来的潜在影响。

      到现在为止,Android中ORM框架也已经有很多,比如ORMLite,Litepal,  androrm,SugarORM, GreenDAO,ActiveAndroid, Realm等等。对于他们之间的对比,可能各有长短,所谓存在即为合理。其中,ORMLite应该是使用较为广泛的一个,接下来我将通过几篇文章,结合ORMLIte的官方文档和源代码对这个框架进行分析。才疏学浅,如果有不足的地方,还请批评指正。

      ORMLite官网: http://ormlite.com/,下载jar包和实例。将jar包加入项目中。

      第一篇,我先结合官方实例和自己的demo让大家感受一下ORMLite的魅力,并熟悉整个流程。

      尊重原创,转载请说明出处,谢谢! http://blog.csdn.net/oyangyujun


一、定义实体类

1. 注解属性和类名,对应数据库字段和表明。

    

2. 给定一个无参构造函数,以便查询返回实体对象。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_1 name=ZeroClipboardMovie_1 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=1&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. @DatabaseTable(tableName = "person")  

  2. public class Person implements Serializable{  

  3.       

  4.     private static final long serialVersionUID = 1L;  

  5.       

  6.     @DatabaseField(generatedId = true)  

  7.     int id;  

  8.     @DatabaseField(canBeNull = true, defaultValue = "name")  

  9.     String name;  

  10.     @DatabaseField(canBeNull = true, defaultValue = "sex")  

  11.     String sex;  

  12.     @DatabaseField(canBeNull = true, defaultValue = "age")  

  13.     String age;  

  14.     @DatabaseField(canBeNull = true, defaultValue = "address")  

  15.     String address;  

  16.     @DatabaseField(canBeNull = true, defaultValue = "phone")  

  17.     String phone;  

  18.     @DatabaseField(canBeNull = true, defaultValue = "qq")  

  19.     String qq;  

  20.     @DatabaseField(canBeNull = true, defaultValue = "testField")  

  21.         String testField;  

  22.     @DatabaseField(canBeNull = true, defaultValue = "testField2")  

  23.         String testField2;  

  24.       

  25.     public Person(){  

  26.     }  


二、生成数据库配置文件

1.  先在res/raw下创建文件ormlite_config.txt

2.  继承OrmLiteCongifUtil类创建DatabaseConfigUtil工具了类,这个工具类用于生成数据库结构信息。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_2 name=ZeroClipboardMovie_2 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=2&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public class DatabaseConfigUtil extends OrmLiteConfigUtil {  

  2.   

  3.     public static void main(String[] args) throws SQLException, IOException {  

  4.         writeConfigFile("ormlite_config.txt");  

  5.     }  

  6.       

  7. }  

3.  在java本地环境下运行该类,不能直接运行android项目。本地环境配置的方法是,右键-》Run Configurations进入运行配置面板如下,注意看是否为当前项目的该工具类。

ORMLite完全解析(一)_第1张图片

4.  选择JRE,选中Alternate JRE,指定使用的JRE版本,官方文档中说1.5或者1.6,当然,高版本也是可以的。

   ORMLite完全解析(一)_第2张图片

5.  选择Classpath,选中Bootstrap Entries下的android,remove掉。切记保留User Entries下的文件。否则会报NoClassDefFoundError, 这里其实就是取消android应用程序的入口,直接将上面的工具类作为程序入口。

ORMLite完全解析(一)_第3张图片

6. 最后直接run,运行完成后会在ormlite_config.txt中生成下面的配置文件内容。

ORMLite完全解析(一)_第4张图片

这个文件是数据库升级更新的依据。这样做的原因是,运行时注解是非常号资源的过程,程序运行时通过反射获取数据表结构维护数据库信息会严重影响效率,虽然OrmLite说明其注解比Java自身的注解机制速度提高了近20倍,不过还是推荐使用这种配置文件的方式。


三、创建数据库辅助类OrmLiteSqliteOpenHelper

1.  创建OrmLite数据库的方式和通过SqliteOpenHelper的维护数据库的方式基本相同,因为OrmLiteSqliteOpenHelper是SqliteOpenHelper的直接子类。我们在项目中使用时需要继承OrmLiteSqliteOpenHelper,重写onCreate和onUpgrade方法。不过OrmLiteSqliteOpenHelper类中这两个方法都比SqliteOpenHelper中多了一个ConnectionSource参数。从字面量理解这个参数主要是用于数据库的升级更新和创建DAO。注意,每次数据模型有变化是,都必须运行OrmLiteCongifUtil工具类更新配置文件和升级数据库版本号,并在onUpgrade中完成相关操作。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_3 name=ZeroClipboardMovie_3 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=3&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public class DatabaseHelper extends OrmLiteSqliteOpenHelper {  

  2.   

  3.     // name of the database file for your application -- change to something appropriate for your app  

  4.     private static final String DATABASE_NAME = "helloAndroid.db";  

  5.     // any time you make changes to your database objects, you may have to increase the database version  

  6.     private static final int DATABASE_VERSION = 3;  

  7.   

  8.     // the DAO object we use to access the SimpleData table  

  9.     private Dao<SimpleData, Integer> simpleDao = null;  

  10.     private RuntimeExceptionDao<SimpleData, Integer> simpleRuntimeDao = null;  

  11.   

  12.     public DatabaseHelper(Context context) {  

  13.         super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);  

  14.     }  

  15.   

  16.     /** 

  17.      * This is called when the database is first created. Usually you should call createTable statements here to create 

  18.      * the tables that will store your data. 

  19.      */  

  20.     @Override  

  21.     public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {  

  22.         try {  

  23.             Log.i(DatabaseHelper.class.getName(), "onCreate");  

  24.             TableUtils.createTable(connectionSource, SimpleData.class);  

  25.         } catch (SQLException e) {  

  26.             Log.e(DatabaseHelper.class.getName(), "Can't create database", e);  

  27.             throw new RuntimeException(e);  

  28.         }  

  29.   

  30.         // here we try inserting data in the on-create as a test  

  31.         RuntimeExceptionDao<SimpleData, Integer> dao = getSimpleDataDao();  

  32.         long millis = System.currentTimeMillis();  

  33.         // create some entries in the onCreate  

  34.         SimpleData simple = new SimpleData(millis);  

  35.         dao.create(simple);  

  36.         simple = new SimpleData(millis + 1);  

  37.         dao.create(simple);  

  38.         Log.i(DatabaseHelper.class.getName(), "created new entries in onCreate: " + millis);  

  39.     }  

  40.   

  41.     /** 

  42.      * This is called when your application is upgraded and it has a higher version number. This allows you to adjust 

  43.      * the various data to match the new version number. 

  44.      */  

  45.     @Override  

  46.     public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {  

  47.         try {  

  48.             Log.i(DatabaseHelper.class.getName(), "onUpgrade");  

  49.             TableUtils.dropTable(connectionSource, SimpleData.classtrue);  

  50.             // after we drop the old databases, we create the new ones  

  51.             onCreate(db, connectionSource);  

  52.         } catch (SQLException e) {  

  53.             Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);  

  54.             throw new RuntimeException(e);  

  55.         }  

  56.     }  

  57.   

  58.     /** 

  59.      * Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached 

  60.      * value. 

  61.      */  

  62.     public Dao<SimpleData, Integer> getDao() throws SQLException {  

  63.         if (simpleDao == null) {  

  64.             simpleDao = getDao(SimpleData.class);  

  65.         }  

  66.         return simpleDao;  

  67.     }  

  68.   

  69.     /** 

  70.      * Returns the RuntimeExceptionDao (Database Access Object) version of a Dao for our SimpleData class. It will 

  71.      * create it or just give the cached value. RuntimeExceptionDao only through RuntimeExceptions. 

  72.      */  

  73.     public RuntimeExceptionDao<SimpleData, Integer> getSimpleDataDao() {  

  74.         if (simpleRuntimeDao == null) {  

  75.             simpleRuntimeDao = getRuntimeExceptionDao(SimpleData.class);  

  76.         }  

  77.         return simpleRuntimeDao;  

  78.     }  

  79.   

  80.     /** 

  81.      * Close the database connections and clear any cached DAOs. 

  82.      */  

  83.     @Override  

  84.     public void close() {  

  85.         super.close();  

  86.         simpleDao = null;  

  87.         simpleRuntimeDao = null;  

  88.     }  

  89. }  

表升级对数据库数据的影响怎么解决?目前是什么情况?


四、获得DAO对象

       获得DAO的方式有两种。

      1.   通过OrmLiteSqliteOpenHelper暴露接口获得,OrmLiteSqliteOpenHelper中默认封装了getDao(Class<T> clazz)方法和getRuntimeExceptionDao(Class<T> clazz)方法便于获得DAO对象。这两个方法本质上是一样的都是通过DAOManage获得对应的DAO对象:

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_4 name=ZeroClipboardMovie_4 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=4&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1.        /** 

  2.  * Get a DAO for our class. This uses the {@link DaoManager} to cache the DAO for future gets. 

  3.  *  

  4.  * <p> 

  5.  * NOTE: This routing does not return Dao<T, ID> because of casting issues if we are assigning it to a custom DAO. 

  6.  * Grumble. 

  7.  * </p> 

  8.  */  

  9. public <D extends Dao<T, ?>, T> D getDao(Class<T> clazz) throws SQLException {  

  10.     // special reflection fu is now handled internally by create dao calling the database type  

  11.     Dao<T, ?> dao = DaoManager.createDao(getConnectionSource(), clazz);  

  12.     @SuppressWarnings("unchecked")  

  13.     D castDao = (D) dao;  

  14.     return castDao;  

  15. }  

  16.   

  17. /** 

  18.  * Get a RuntimeExceptionDao for our class. This uses the {@link DaoManager} to cache the DAO for future gets. 

  19.  *  

  20.  * <p> 

  21.  * NOTE: This routing does not return RuntimeExceptionDao<T, ID> because of casting issues if we are assigning it to 

  22.  * a custom DAO. Grumble. 

  23.  * </p> 

  24.  */  

  25. public <D extends RuntimeExceptionDao<T, ?>, T> D getRuntimeExceptionDao(Class<T> clazz) {  

  26.     try {  

  27.         Dao<T, ?> dao = getDao(clazz);  

  28.         @SuppressWarnings({ "unchecked""rawtypes" })  

  29.         D castDao = (D) new RuntimeExceptionDao(dao);  

  30.         return castDao;  

  31.     } catch (SQLException e) {  

  32.         throw new RuntimeException("Could not create RuntimeExcepitionDao for class " + clazz, e);  

  33.     }  

  34. }  


       他们的区别在于对处理异常的方式不一样。如RuntimeExceptionDao的类注释所述,RuntimeExceptionDao只是对异常信息进行了包装处理,并将其作为运行时异常重新抛出。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_5 name=ZeroClipboardMovie_5 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=5&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. /** 

  2.  * Proxy to a {@link Dao} that wraps each Exception and rethrows it as RuntimeException. You can use this if your usage 

  3.  * pattern is to ignore all exceptions. That's not a pattern that I like so it's not the default. 

  4.  *  

  5.  * <p> 

  6.  *  

  7.  * <pre> 

  8.  * RuntimeExceptionDao<Account, String> accountDao = RuntimeExceptionDao.createDao(connectionSource, Account.class); 

  9.  * </pre> 

  10.  *  

  11.  * </p> 

  12.  *  

  13.  * @author graywatson 

  14.  */  

  15. public class RuntimeExceptionDao<T, ID> implements CloseableIterable<T> {  


       如果我们应用中的组件是通过继承OrmLiteBaseActivity等类的方式来使用ORMLite的话,可以使用派生出来的组件已有的getHelper()方法直接获得OrmLiteSqliteOpenHelper对象,然后调用我们在OrmLiteSqliteOpenHelper中暴露的接口获取对应的DAO对象。如下:

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_6 name=ZeroClipboardMovie_6 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=6&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. RuntimeExceptionDao<SimpleData, Integer> simpleDao = getHelper().getSimpleDataDao();  


   2.  第二种获得DAO的方式是直接通过DAOManager获得。使用这种方式需要一个ConnectionSource参数,和实体类的Class对象,ConnectionSource参数可以通过OrmLiteSqliteOpenHelper的getConnectionSource()方法获得。这两个方法定义如下。

   DAOManager中的createDAO方法。

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_7 name=ZeroClipboardMovie_7 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=7&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1.        /** 

  2.  * Helper method to create a DAO object without having to define a class. This checks to see if the DAO has already 

  3.  * been created. If not then it is a call through to {@link BaseDaoImpl#createDao(ConnectionSource, Class)}. 

  4.  */  

  5. public synchronized static <D extends Dao<T, ?>, T> D createDao(ConnectionSource connectionSource, Class<T> clazz)  

  6.         throws SQLException {  

   OrmLiteSqliteOpenHelper中的getConnectionSource方法。

  

[html] view plaincopy

<EMBED id=ZeroClipboardMovie_8 name=ZeroClipboardMovie_8 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=8&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1.        protected AndroidConnectionSource connectionSource = new AndroidConnectionSource(this);  

  2.        /**  

  3.  * Get the connection source associated with the helper.  

  4.  */  

  5. public ConnectionSource getConnectionSource() {  

  6.     if (!isOpen) {  

  7.         // we don't throw this exception, but log it for debugging purposes  

  8.         logger.warn(new IllegalStateException(), "Getting connectionSource was called after closed");  

  9.     }  

  10.     return connectionSource;  

  11. }  


五、在Activity中使用DAO操作数据库。

      1.  获得Helper对象

       通过上面的分析可知,DAO可以通过Helper对象获得,也建议使用这种方式。而且使用DAO操作数据库才是我们的想要的过程,对于这一点,ORMLite本身也考虑的非常周到,他给我们提供了一些相应的快捷实现类,包括OrmLiteBaseActivity, OrmLiteBaseActivityGroup, OrmLiteBaseListActivity, OrmLiteBaseService, OrmLiteBaseTabActivity等。仔细分析其源码,发现实现方式都是一样的,这里以OrmLiteBaseActivity为例。完整源代码如下:

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_9 name=ZeroClipboardMovie_9 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=9&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. /** 

  2.  * Base class to use for activities in Android. 

  3.  *  

  4.  * You can simply call {@link #getHelper()} to get your helper class, or {@link #getConnectionSource()} to get a 

  5.  * {@link ConnectionSource}. 

  6.  *  

  7.  * The method {@link #getHelper()} assumes you are using the default helper factory -- see {@link OpenHelperManager}. If 

  8.  * not, you'll need to provide your own helper instances which will need to implement a reference counting scheme. This 

  9.  * method will only be called if you use the database, and only called once for this activity's life-cycle. 'close' will 

  10.  * also be called once for each call to createInstance. 

  11.  *  

  12.  * @author graywatson, kevingalligan 

  13.  */  

  14. public abstract class OrmLiteBaseActivity<H extends OrmLiteSqliteOpenHelper> extends Activity {  

  15.   

  16.     private volatile H helper;  

  17.     private volatile boolean created = false;  

  18.     private volatile boolean destroyed = false;  

  19.     private static Logger logger = LoggerFactory.getLogger(OrmLiteBaseActivity.class);  

  20.   

  21.     /** 

  22.      * Get a helper for this action. 

  23.      */  

  24.     public H getHelper() {  

  25.         if (helper == null) {  

  26.             if (!created) {  

  27.                 throw new IllegalStateException("A call has not been made to onCreate() yet so the helper is null");  

  28.             } else if (destroyed) {  

  29.                 throw new IllegalStateException(  

  30.                         "A call to onDestroy has already been made and the helper cannot be used after that point");  

  31.             } else {  

  32.                 throw new IllegalStateException("Helper is null for some unknown reason");  

  33.             }  

  34.         } else {  

  35.             return helper;  

  36.         }  

  37.     }  

  38.   

  39.     /** 

  40.      * Get a connection source for this action. 

  41.      */  

  42.     public ConnectionSource getConnectionSource() {  

  43.         return getHelper().getConnectionSource();  

  44.     }  

  45.   

  46.     @Override  

  47.     protected void onCreate(Bundle savedInstanceState) {  

  48.         if (helper == null) {  

  49.             helper = getHelperInternal(this);  

  50.             created = true;  

  51.         }  

  52.         super.onCreate(savedInstanceState);  

  53.     }  

  54.   

  55.     @Override  

  56.     protected void onDestroy() {  

  57.         super.onDestroy();  

  58.         releaseHelper(helper);  

  59.         destroyed = true;  

  60.     }  

  61.   

  62.     /** 

  63.      * This is called internally by the class to populate the helper object instance. This should not be called directly 

  64.      * by client code unless you know what you are doing. Use {@link #getHelper()} to get a helper instance. If you are 

  65.      * managing your own helper creation, override this method to supply this activity with a helper instance. 

  66.      *  

  67.      * <p> 

  68.      * <b> NOTE: </b> If you override this method, you most likely will need to override the 

  69.      * {@link #releaseHelper(OrmLiteSqliteOpenHelper)} method as well. 

  70.      * </p> 

  71.      */  

  72.     protected H getHelperInternal(Context context) {  

  73.         @SuppressWarnings({ "unchecked""deprecation" })  

  74.         H newHelper = (H) OpenHelperManager.getHelper(context);  

  75.         logger.trace("{}: got new helper {} from OpenHelperManager"this, newHelper);  

  76.         return newHelper;  

  77.     }  

  78.   

  79.     /** 

  80.      * Release the helper instance created in {@link #getHelperInternal(Context)}. You most likely will not need to call 

  81.      * this directly since {@link #onDestroy()} does it for you. 

  82.      *  

  83.      * <p> 

  84.      * <b> NOTE: </b> If you override this method, you most likely will need to override the 

  85.      * {@link #getHelperInternal(Context)} method as well. 

  86.      * </p> 

  87.      */  

  88.     protected void releaseHelper(H helper) {  

  89.         OpenHelperManager.releaseHelper();  

  90.         logger.trace("{}: helper {} was released, set to null"this, helper);  

  91.         this.helper = null;  

  92.     }  

  93.   

  94.     @Override  

  95.     public String toString() {  

  96.         return getClass().getSimpleName() + "@" + Integer.toHexString(super.hashCode());  

  97.     }  

  98. }  


通过源码可以知道,这些扩展类,都是内部持有了一个对应的OrmLiteSqliteOpenHelper对象。并在Activity的onCreate方法中初始化,在onDestroyed方法中销毁释放资源。

这里涉及到一个OpenHelperManager类,这个类是OrmLiteSqliteOpenHelper的工具类,用于管理数据库连接。完整的解释如下:

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_10 name=ZeroClipboardMovie_10 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=10&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. /** 

  2.  * This helps organize and access database connections to optimize connection sharing. There are several schemes to 

  3.  * manage the database connections in an Android app, but as an app gets more complicated, there are many potential 

  4.  * places where database locks can occur. This class allows database connection sharing between multiple threads in a 

  5.  * single app. 

  6.  *  

  7.  * This gets injected or called with the {@link OrmLiteSqliteOpenHelper} class that is used to manage the database 

  8.  * connection. The helper instance will be kept in a static field and only released once its internal usage count goes 

  9.  * to 0. 

  10.  *  

  11.  * The {@link SQLiteOpenHelper} and database classes maintain one connection under the hood, and prevent locks in the 

  12.  * java code. Creating multiple connections can potentially be a source of trouble. This class shares the same 

  13.  * connection instance between multiple clients, which will allow multiple activities and services to run at the same 

  14.  * time. 

  15.  *  

  16.  * Every time you use the helper, you should call {@link #getHelper(Context)} or {@link #getHelper(Context, Class)}. 

  17.  * When you are done with the helper you should call {@link #releaseHelper()}. 

  18.  *  

  19.  * @author graywatson, kevingalligan 

  20.  */  

  21. public class OpenHelperManager {  

翻译:这个类用于组织和获取数据库连接,优化连接共享。在一个app中,可能有多个模式来管理数据库连接,但是当app变得愈加复杂时,就会存在很多潜在的数据库锁发生点。这个类允许数据库连接在同一app的多个线程中共享。

       这个用于注入OrmLiteSqliteOpenHelper,之后,OrmLiteSqliteOpenHelper的实例会作为一个静态属性被持有。只有当其内部的使用数变为0时才会被释放。

       SQLiteOpenHelper和数据库类在这个引擎下持有一个连接,并且防止java代码中发生死锁。创建多个连接可能会存在潜在的安全问题。这个类在多个客户端中持有相同的连接实例, 并允许多个Activity和service在同一时刻运行。

每次使用这个Helper是,你应该调用getHelper(Context)或者getHelper(Context,Class),操作完成时,应该调用releaseHelper()进行释放。

       处理上面的解释外,可以注意到,OrmLiteBaseActivity中的OrmLiteSqliteOpenHelper对象被修饰为volatile。这个修饰符的作用是修饰被不同线程访问和修改的变量。如果没有volatile,基本上会导致这样的结果:要么无法编写多线程程序,要么编译器失去大量优化的机会。


        同时也可以想到,如果我们不想让自己的Activity继承OrmLite中的基类,大可按照其内部实现方式,将写代码迁移到我们自己的BaseActivity中。


    2.  通过Helper获得的DAO对象操作数据库

        到此为止,我们知道了怎么获得Helper并通过Helper获得DAO,或者RuntimeExceptionDao,下面是对数据库进行操作的基本方式。

        官方的HelloAndroid中使用到了三种基本操作,插入,查询,删除。

        方式如下: 插入数据的代码在Helper类的onCreate中,当然在其他地方是毫无疑问的可以的。创建对象,给对象赋值,然后直接通过DAO进行create即可(看上面Helper类的实现)。

       其次是查询,官方实例中查询和删除在HelloAndroid中进行的,都是直接通过Dao的实例调用响应的方法:

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_11 name=ZeroClipboardMovie_11 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=11&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1.               // get our dao  

  2. RuntimeExceptionDao<SimpleData, Integer> simpleDao = getHelper().getSimpleDataDao();  

  3. // query for all of the data objects in the database  

  4. List<SimpleData> list = simpleDao.queryForAll();  

  5. // our string builder for building the content-view  

  6. StringBuilder sb = new StringBuilder();  

  7. sb.append("got ").append(list.size()).append(" entries in ").append(action).append("\n");  

  8.   

  9. // if we already have items in the database  

  10. int simpleC = 0;  

  11. for (SimpleData simple : list) {  

  12.     sb.append("------------------------------------------\n");  

  13.     sb.append("[").append(simpleC).append("] = ").append(simple).append("\n");  

  14.     simpleC++;  

  15. }  

  16. sb.append("------------------------------------------\n");  

  17. for (SimpleData simple : list) {  

  18.     simpleDao.delete(simple);  

  19.     sb.append("deleted id ").append(simple.id).append("\n");  

  20.     Log.i(LOG_TAG, "deleting simple(" + simple.id + ")");  

  21.     simpleC++;  

  22. }  

    当然快捷操作方法还有很多,使用方式都是类似的,后面再分析。

你可能感兴趣的:(ORMLite完全解析(一))