前言
android开发中,免不了使用数据库,使用第三方开源框架,能够极大的提高我们的开发效率
本文使用ORMLite数据库,开发工具使用Android studio
一、环境变量配置
1.使用jar包,分别下载ormlite-android-5.0.jar和ormlite-core-5.0.jar(去下载),放到libs目录下;
2.使用gradle,如下图
二、项目目录说明
--bean:bean包下为实体类,每一个实体对应一个数据库表,如User.java对应数据库的tb_user表,bean下有几个实体类就有几个数据库表
--db:db包下为数据库操作封装,DatabseHelper是一个单利模式,对外只提供一个对象,地位相当于于数据库中的SQLiteOpenHelper,XXDao封装了对数据库的操作,如UserDao操作User表,增删改查
--utils:utils包下为日志输出工具
---AndroidTest:AndroidTest下对数据库进行测试用例分析
三、项目代码
3.1:编写Bean类
@DatabaseTable(tableName = "tb_article") public class Article { @DatabaseField(generatedId = true) private int id; @DatabaseField private String title; @DatabaseField(canBeNull = true, foreign = true, columnName = "user_id", foreignAutoRefresh = true) 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; } @Override public String toString() { return "Article [id=" + id + ", title=" + title + ", user=" + user + "]"; } }首先在User类上添加@DatabaseTable(tableName = "tb_article"),标明这是数据库中的一张表,标明为tb_article
然后分别在属性上添加@DatabaseField(columnName = "name") ,columnName的值为该字段在数据中的列名
@DatabaseField(generatedId = true) ,generatedId 表示id为主键且自动生成
3.2: 编写Dao类
3.2.1 编写DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final String TABLE_NAME = "sqlite-test.db"; private Map<String, Dao> daos = new HashMap<String, Dao>(); private DatabaseHelper(Context context) { super(context, TABLE_NAME, null, 4); } @Override public 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(); } } @Override public 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; /** * 单例获取该Helper * * @param context * @return */ public static synchronized DatabaseHelper 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); daos.put(className, dao); } return dao; } /** * 释放资源 */ @Override public void close() { super.close(); for (String key : daos.keySet()) { Dao dao = daos.get(key); dao = null; } } }
DatabaseHelper继承OrmLiteSqliteOpenHelper,其实就是间接继承了SQLiteOpenHelper
然后需要实现两个方法:
1、onCreate(SQLiteDatabase database,ConnectionSource connectionSource)
创建表,我们直接使用ormlite提供的TableUtils.createTable(connectionSource, User.class);进行创建~
2、onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)
更新表,使用ormlite提供的TableUtils.dropTable(connectionSource, User.class, true);进行删除操作~
删除完成后,别忘了,创建操作:onCreate(database, connectionSource);
3.2.2 编写XXDao
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(); } } /** * 添加一个Article * * @param article */ public void add(Article article) { try { articleDaoOpe.create(article); } catch (SQLException e) { e.printStackTrace(); } } /** * 通过Id得到一个Article * * @param id * @return */ @SuppressWarnings("unchecked") public Article getArticleWithUser(int id) { Article article = null; try { article = articleDaoOpe.queryForId(id); helper.getDao(User.class).refresh(article.getUser()); } catch (SQLException e) { e.printStackTrace(); } return article; } /** * 通过Id得到一篇文章 * * @param id * @return */ public Article get(int id) { Article article = null; try { article = articleDaoOpe.queryForId(id); } catch (SQLException e) { e.printStackTrace(); } return article; } /** * 通过UserId获取所有的文章 * * @param userId * @return */ public List<Article> listByUserId(int userId) { try { return articleDaoOpe.queryBuilder().where().eq("user_id", userId) .query(); } catch (SQLException e) { e.printStackTrace(); } return null; } }此类处理Bean对应的事件,如增删改查等
四、对数据库进行单元测试
去下载源码