OrmLite数据库使用

Android中有很多操作SQLite数据库的框架,现在最常见、最常用的是OrmLite和GreenDAO。OrmLite相比与GreenDAO来说是一个轻量级的框架,而且学习成本相对较低。

要使用OrmLite,首先需要导入OrmLite的依赖:在build.gradle中加入以下代码:

引入依赖

implementation files('libs/ormlite-android-5.0.jar')
implementation files('libs/ormlite-core-5.0.jar')

OrmLite需要我们自己实现一个类似原生操作SQLite数据库的DatabaseHelper,但必须继承自OrmLite为我们提供的OrmLiteSqliteOpenHelper。以下是一个功能比较齐全,性能相对也比较好的实例,这个实例不仅仅起到了创建数据库和更新数据库的操作,代码如下:

创建数据库

需要创建一个类来继承OrmLiteSqliteOpenHelper,完成数据的创建以及升级
DetailDataOpenHelper.java

package com.example.edwardadmin.ormdatabase.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.example.edwardadmin.ormdatabase.entity.IdentityInfo;
import com.example.edwardadmin.ormdatabase.entity.PersonInfo;
import com.example.edwardadmin.ormdatabase.entity.PersonToken;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

public class DetailDataOpenHelper extends OrmLiteSqliteOpenHelper {

    //定义数据库存放位置,便于以后查看
    public static final String DATABASE_PATH = Environment.getExternalStorageDirectory() + "/detail.db";
    //定义数据库的版本号,当数据库需要升级时进行更改
    public static final int DATABASE_VERSION = 1;
    //创建DetailDataOpenHelper实例
    private static DetailDataOpenHelper instance;

    public static DetailDataOpenHelper getInstance(Context mContext) {
        if (instance == null) {
            synchronized (DetailDataOpenHelper.class) {
                if (instance == null) {
                    instance = new DetailDataOpenHelper(mContext);
                }
            }
        }
        return instance;
    }

    public DetailDataOpenHelper(Context context) {
        super(context, DATABASE_PATH, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, PersonInfo.class);
            TableUtils.createTable(connectionSource, IdentityInfo.class);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource, IdentityInfo.class, false);
            TableUtils.createTable(connectionSource, IdentityInfo.class);
            
            TableUtils.createTable(connectionSource, PersonInfo.class);
            TableUtils.dropTable(connectionSource, PersonInfo.class, false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

onCreate 初始化数据库

  • 调用TableUtils.createTable(connectionSource, PersonInfo.class);

onUpgrade 升级数据库

  • 先删除表,调用TableUtils.dropTable(connectionSource, IdentityInfo.class, false);
  • 然后创建表,调用TableUtils.createTable(connectionSource, IdentityInfo.class);

创建JavaBean

PersonInfo.java

package com.example.edwardadmin.ormdatabase.entity;

import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;

import java.io.Serializable;
import java.util.ArrayList;

@DatabaseTable(tableName = "t_person")
public class PersonInfo implements Serializable {

    @DatabaseField(columnName = "id", generatedId = true)
    public int id;

    @DatabaseField(columnName = "personName")
    private String personName;

    @DatabaseField(columnName = "personSex")
    private String personSex;

    @DatabaseField(columnName = "personAge")
    private String personAge;

    @DatabaseField(columnName = "personHeight")
    private String personHeight;

    @DatabaseField(columnName = "personNative")
    private String personNative;

    @DatabaseField(columnName = "personNumber")
    private String personNumber;

    @DatabaseField(columnName = "personImage")
    private String personImage;

    /**
     * 创建空的构造函数,否则报错
     */
    public PersonInfo() {
    }

    public PersonInfo(String personName, String personSex, String personAge, String personHeight, String personNative, String personNumber) {
        this.personName = personName;
        this.personSex = personSex;
        this.personAge = personAge;
        this.personHeight = personHeight;
        this.personNumber = personNumber;
        this.personNative = personNative;
    }

    public PersonInfo(String personName, String personSex, String personAge, String personHeight, String personNative, String personNumber, String personImage) {
        this.personName = personName;
        this.personSex = personSex;
        this.personAge = personAge;
        this.personHeight = personHeight;
        this.personNumber = personNumber;
        this.personNative = personNative;
        this.personImage = personImage;
    }

    public String getPersonName() {
        return personName;
    }

    public String getPersonSex() {
        return personSex;
    }

    public String getPersonAge() {
        return personAge;
    }

    public String getPersonHeight() {
        return personHeight;
    }

    public String getPersonNative() {
        return personNative;
    }

    public String getPersonNumber() {
        return personNumber;
    }

    public String getPersonImage() {
        return personImage;
    }

    @Override
    public String toString() {
        return "PersonInfo{" +
                "id=" + id +
                ", personName='" + personName + '\'' +
                ", personSex='" + personSex + '\'' +
                ", personAge='" + personAge + '\'' +
                ", personHeight='" + personHeight + '\'' +
                ", personNative='" + personNative + '\'' +
                ", personNumber='" + personNumber + '\'' +
                ", personImage='" + personImage + '\'' +
                ", personTokens=" + personTokens +
                '}';
    }
}

注解含义

  • @DatabaseTable(tableName = "t_person"),此处指创建了一个的t_person的表
  • @DatabaseField(columnName = "id", generatedId = true),此处指创建了名为id的字段名,且是主键
  • @DatabaseField(columnName = "personName"),此处指创建了名为personName的字段名

常用参数

  • generatedId = true 主键,自动生成的id 该注解下的字段必须是整形(int long)
  • id = true 主键
  • unique = true 唯一约束 默认false
  • columnName = "name" 表字段名,默认为变量名称
  • canBeNull = false 非空约束,默认为true,可以为null,设为false就不能为null
  • foreign = true 外键引用,字段不能是一个原始类型,应该定义一个对象当做外键引用,在外键对象的类中,必须要有一
    个ID字段(ID, generatedId,generatedIdSequence)
  • foreignAutoRefersh = true 在使用外键引用时,由于ormlite的外键引用使用的是对象,所以添加这个字段的话在查询,会把
    外键的对象数据都查询回来,否则外键数据就只有那个对象的主键有值,其余的值都是null
  • defaultValue = "小明" 默认值
  • index = true 建立索引 默认为false
  • uniqueIndex = true 唯一索引 默认为false

创建PersonDao

PersonDao.java

package com.example.edwardadmin.ormdatabase.database;

import android.content.Context;

import com.example.edwardadmin.ormdatabase.entity.PersonInfo;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;

public class PersonDao {

    private Dao personInfoDao;

    public Dao getPersonInfoDao(Context mContext) {
        if (personInfoDao == null) {
            personInfoDao = createPersonDao(mContext);
        }
        return personInfoDao;
    }

    private Dao createPersonDao(Context mContext) {
        try {
            return DetailDataOpenHelper.getInstance(mContext).getDao(PersonInfo.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

  • 调用createPersonDao方法,通过DetailDataOpenHelper.getInstance(mContext).getDao(PersonInfo.class);

创建IPersonOperation接口

IPersonOperation.java

package com.example.edwardadmin.ormdatabase.database;

import com.example.edwardadmin.ormdatabase.entity.PersonInfo;

import java.util.ArrayList;

public interface IPersonOperation {

    boolean insertPersonData(PersonInfo personInfo);
    boolean deletePersonData(PersonInfo personInfo);
    ArrayList queryPersonData();
    PersonInfo queryPersonDataByPersonNumber(String personNumber);
}

  • 插入PersonInfo对象到数据库
  • 从数据库中删除PerosnInfo对象
  • 从数据库中查询所有的PersonInfo对象
  • 根据personNumber查询PersonInfo对象

创建PersonInfoOperationTask

PersonInfoOperationTask.java

package com.example.edwardadmin.ormdatabase.database;

import android.content.Context;
import android.util.Log;

import com.example.edwardadmin.ormdatabase.entity.PersonInfo;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;

public class PersonInfoOperationTask extends BaseOperationTask implements IPersonOperation {

    private Dao personInfoDao;
    private ArrayList mAllPersonData;

    public PersonInfoOperationTask(Context mContext) {
        super(mContext);
        personInfoDao = new PersonDao().getPersonInfoDao(mContext);
    }

    @Override
    public boolean insertPersonData(PersonInfo personInfo) {
        Savepoint savepoint = null;
        try {
            savepoint = androidDatabaseConnection.setSavePoint("start");
            androidDatabaseConnection.setAutoCommit(false);
            int startResult = personInfoDao.create(personInfo);
            androidDatabaseConnection.commit(savepoint);
            if (startResult != -1) {
                return true;
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                androidDatabaseConnection.rollback(savepoint);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public boolean deletePersonData(PersonInfo personInfo) {
        Savepoint savePoint = null;
        try {
            savePoint = androidDatabaseConnection.setSavePoint("start");
            androidDatabaseConnection.setAutoCommit(false);
            int deleteResult = personInfoDao.delete(personInfo);
            androidDatabaseConnection.commit(savePoint);
            if (deleteResult != -1) {
                return true;
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                androidDatabaseConnection.rollback(savePoint);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            return false;
        }
    }

    @Override
    public ArrayList queryPersonData() {
        mAllPersonData = new ArrayList<>();
        Savepoint savepoint = null;
        try {
            savepoint = androidDatabaseConnection.setSavePoint("start");
            androidDatabaseConnection.setAutoCommit(false);
            mAllPersonData = (ArrayList) personInfoDao.queryBuilder().orderBy("id", false).query();
            androidDatabaseConnection.commit(savepoint);
            return mAllPersonData;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                androidDatabaseConnection.rollback(savepoint);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public PersonInfo queryPersonDataByPersonNumber(String personNumber) {
        PersonInfo personInfo = null;
        Savepoint savepoint = null;
        try {
            savepoint = androidDatabaseConnection.setSavePoint("start");
            ArrayList list = (ArrayList) personInfoDao.queryForAll();
            for(int index = 0; index < list.size(); index ++) {
                PersonInfo info1 = list.get(index);
                if (info1.getPersonNumber().equals(personNumber)) {
                    personInfo = info1;
                }
            }
            androidDatabaseConnection.setAutoCommit(false);
            mAllPersonData = (ArrayList) personInfoDao.queryBuilder().orderBy("id", false).query();
            androidDatabaseConnection.commit(savepoint);
            return personInfo;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                androidDatabaseConnection.rollback(savepoint);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
}

  • SavePoint 创建事务保存点
  • AndroidDatabaseConnection 获取数据库连接
  • 操作成功,提交事务,操作失败,回滚事务

数据模拟

创建PersonInteractorImpl.java

package com.example.edwardadmin.ormdatabase.fragment;

import android.content.Context;
import android.util.Log;

import com.example.edwardadmin.ormdatabase.database.PersonInfoOperationTask;
import com.example.edwardadmin.ormdatabase.database.PersonTokenOperationTask;
import com.example.edwardadmin.ormdatabase.entity.PersonInfo;

import java.util.ArrayList;

public class PersonInteractorImpl implements IPersonInteractor {

    private PersonInfoOperationTask personInfoOperationTask;
    private PersonTokenOperationTask personTokenOperationTask;

    public PersonInteractorImpl(Context mContext) {
        personInfoOperationTask = new PersonInfoOperationTask(mContext);
        personTokenOperationTask = new PersonTokenOperationTask(mContext);
    }

    /**
     * 加载数据,从数据库中查询数据
     * @param loadingFinishedListener
     */
    @Override
    public void loadPersonData(onLoadingFinishedListener loadingFinishedListener) {
        ArrayList personInfoArrayList = personInfoOperationTask.queryPersonData();
        if (personInfoArrayList != null) {
            loadingFinishedListener.loadPersonDataSuccess(personInfoArrayList);
        } else {
            loadingFinishedListener.loadPersonDataError();
        }
    }

    /**
     * 添加数据,将PersonInfo,插入到数据库中
     * @param personInfo
     * @param loadingFinishedListener
     */
    @Override
    public void addPersonData(PersonInfo personInfo, onLoadingFinishedListener loadingFinishedListener) {
        boolean insert = personInfoOperationTask.insertPersonData(personInfo);
        if (insert) {
            loadingFinishedListener.addPersonDataSuccess();
        } else {
            loadingFinishedListener.addPersonDataError();
        }
    }

}

  • 从数据库中查询所有的PersonInfo数据,将获取的ArrayList进行返回,初始化Aapter,更新数据源
  • 根据传入PersonInfo对象,插入到数据库中,如果返回的结果是true,但是插入成功,反之,插入失败。

Github地址:
ORMDataBase:https://github.com/EricWinner/ORMDataBase
有任何问题,欢迎指出.

你可能感兴趣的:(OrmLite数据库使用)