Android 中ORMLite 框架简单封装

前言:

大家在做安卓项目时肯定都会碰到数据库存储,原生的效率上会比较低,为了提高开发效率,大多公司会用一些框架,目前市面上比较流行的框架有ormlite、greenDao、SQLBrite、Realm等,
其中ormlite是JDBC(Java数据库连接)和Android的轻量级ORM java包,而GreenDao则是一种轻快地将对象映射到SQLite数据库的ORM解决方案。

GitHub 地址:https://github.com/lyyRunning/OrmLiteDeOmo

下载ORMLite Jar包(1 和 2 选其一啊)

1.首先去ORMLite官网下载jar包,

2.也可以配置项目依赖的

导入OrmLite的依赖:在build.gradle中加入以下代码:

 //引入ormlite
compile group: 'com.j256.ormlite', name: 'ormlite-core', version: '5.1'
compile group: 'com.j256.ormlite', name: 'ormlite-android', version: '5.1'

ORMLITE 使用:

  1. OrmLite需要我们自己实现一个类似原生操作SQLite数据库的DatabaseHelper,但必须继承自OrmLite为我们提供的OrmLiteSqliteOpenHelper。以下是一个功能比较齐全,性能相对也比较好的实例,这个实例不仅仅起到了创建数据库和更新数据库的操作,代码如下:
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    /**
     * 数据库名称
     */
    private static final String TABLE_NAME = "sqlite-test.db";
    /**
     * 版本号
     */
    private static final int DBVERSION = 2;

    private static Context mContext;
    /**
     * 单例
     */
    private static DatabaseHelper mInstance;


    private DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, DBVERSION);
    }

    /**
     * 初始化
     *
     * @param context
     */
    public static void initOrmLite(Context context) {
        mContext = context;
        getIntence();
    }

    /**
     * 创建数据库表
     *
     * @param database
     * @param connectionSource
     */
    @Override
    public void onCreate(SQLiteDatabase database,
                         ConnectionSource connectionSource) {
        try {
           TableUtils.createTable(connectionSource,  Student.class);
           TableUtils.createTable(connectionSource, User.class);

        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","插入单条数据异常:"+e.getMessage());
        }
    }

    /**
     * 升级数据库
     *
     * @param database
     * @param connectionSource
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource, User.class, true);
            TableUtils.dropTable(connectionSource, Student.class, true);

            onCreate(database, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","插入多条数据异常:"+e.getMessage());

        }
    }


    /**
     * 单例获取该Helper
     *
     * @param
     * @return
     */
    public static synchronized DatabaseHelper getIntence() {

        if (null == mInstance) {
            synchronized (DatabaseHelper.class) {
                if (null == mInstance) {
                    mInstance = new DatabaseHelper(mContext);
                }
            }
        }
        return mInstance;
    }

    /**
     * 获取数据对象
     *
     * @param classz 对应的表实体的字节码对象
     * @return Dao :T:表实体对象类型.ID:对应的表实体中被指定为id字段的属性类型
     * @throws SQLException
     */
    @Override
    public Dao getDao(Class classz) throws SQLException {
        return super.getDao(classz);
    }

}

  1. DaoUtils工具类封装:
public class DaoUtils {

    /**
     * 根据数据表实体查询到的Dao
     * 第一个泛型为数据表实体
     * 第二个泛型为数据表实体中被指定为id的属性的数据类型
     */
    private static Dao mDao;


    /**
     * 单例模式获取实例
     * 必须写入对应的 Bean,每个都要手动写
     */
    public static Dao getInstance(DbBean dbBean) {
        if (null == mDao) {
            try {
                //必须单个实例去判断
                if (dbBean instanceof User) {
                    mDao = DatabaseHelper.getIntence().getDao(User.class);
                }else if (dbBean instanceof Student){
                    mDao = DatabaseHelper.getIntence().getDao(Student.class);
                }

            } catch (SQLException e) {
                e.printStackTrace();
                Log.d("LUO","实例异常:"+e.getMessage());
            }
        }
        return mDao;
    }



    /**
     * 插入单条数据
     *
     * @param dbBean
     */
    public static Boolean  insertData(DbBean dbBean) {
        try {
            //数据更新的行数返回值是 1.否则抛出异常

            int result = getInstance(dbBean).create(dbBean);
            if (result!= -1){
                Toast.makeText(MyApplication.getApplicationInstance(),"插入成功", LENGTH_SHORT).show();
                return true;

            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","插入单行数据异常:"+e.getMessage());
        }
        return false;
    }



    /**
     * 插入多条数据
     *
     * @param userList
     */
    public static Boolean insertListData(DbBean dbBean,List userList) {
        try {
            //数据更新的行数返回值是 1.否则抛出异常
            int result = getInstance(dbBean).create( userList);
            if (result!= -1){
                Toast.makeText(MyApplication.getApplicationInstance(),"插入成功", LENGTH_SHORT).show();

                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","插入多行数据异常:"+e.getMessage());
        }
        return false;
    }


    /**
     * 修改单条数据
     *
     * @param dbBean
     */
    public static Boolean updateData(DbBean dbBean) {
        try {
            //数据更新的行数返回值是 1.否则抛出异常
            int result = getInstance(dbBean).update(dbBean);
            if (result!= -1){
                Toast.makeText(MyApplication.getApplicationInstance(),"修改成功", LENGTH_SHORT).show();

                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","修改单行数据异常:"+e.getMessage());
        }
        return false;
    }




    /**
     * 查询表中所有数据
     *
     * @return
     */
    public static List queryData(DbBean dbBean) {
        List ormTables = null;
        try {
            ormTables = getInstance(dbBean).queryForAll();
            Log.d("LUO","======="+ormTables.size());
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","查询所有数据异常:"+e.getMessage());
        }
        return ormTables;
    }


    /**
     * 自定义查询表中数据
     *  QueryBuilder builder = getInstance().queryBuilder();
     * Where where = builder.where();
     *  where.eq("_id", "111")
     * .and()
     * .eq("name", "aaa");
     */
    public static List queryByCustom(DbBean dbBean) {
        List ormTables = null;
        QueryBuilder builder = getInstance(dbBean).queryBuilder();
        Where where = builder.where();
        try {
            where.eq("_id", "1")
                    .and()
                    .eq("name", "zhy");
            ormTables = builder.query();

        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","查询符合条件数据异常:"+e.getMessage());
        }
        return ormTables;
    }






    /**
     * 通过对象id进行数据删除
     *
     * @param dbBean
     */
    public static Boolean deleteByDbBean(DbBean dbBean) {
        try {
            int result = getInstance(dbBean).delete(dbBean);
            if (result!= -1){
                Toast.makeText(MyApplication.getApplicationInstance(),"删除成功", LENGTH_SHORT).show();

                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","删除单行数据异常:"+e.getMessage());
        }
        return false;
    }



    /**
     * 删除表中所有数据
     */
    public static Boolean deleteAllData(DbBean dbBean) {
        try {
            //数据更新的行数返回值是 1.否则抛出异常
            int result = getInstance(dbBean).deleteBuilder().delete();
            if (result!= -1){
                Toast.makeText(MyApplication.getApplicationInstance(),"删除全部成功", LENGTH_SHORT).show();

                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d("LUO","删除所有数据异常:"+e.getMessage());

        }
        return false;
    }

}

  1. MyApplication初始化本地数据库:
public class MyApplication extends Application {

    public static Context mContex;
    @Override
    public void onCreate() {
        super.onCreate();
        mContex = this;
        initDataBase();

    }

    /**
     * 初始化本地数据库
     */
    private void initDataBase() {

        DatabaseHelper.initOrmLite(this);
    }



    public static Context getApplicationInstance(){
        return mContex;
    }
}
  1. DbBean的使用:
public class DbBean {
}
  1. Userbean的使用:
@DatabaseTable(tableName = "tb_user")
public class User extends DbBean {

    @DatabaseField(generatedId = true)
    private int id;
    @DatabaseField(columnName = "name")
    private String name;
    @DatabaseField(columnName = "desc")
    private String desc;

    public User() {
    }

    public User(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

  1. Student的使用:
@DatabaseTable(tableName = "tb_student")
public class Student extends DbBean {

    @DatabaseField(generatedId = true)
    private int id;
    @DatabaseField(columnName = "name")
    private String name;
    @DatabaseField(columnName = "desc")
    private String desc;

    public Student() {
    }

    public Student(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
  1. 数据库的使用:
public class MainActivity extends AppCompatActivity {
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.button1)
    Button button1;
    @BindView(R.id.button2)
    Button button2;
    @BindView(R.id.button3)
    Button button3;
    @BindView(R.id.button4)
    Button button4;
    @BindView(R.id.button5)
    Button button5;
    @BindView(R.id.button6)
    Button button6;
    @BindView(R.id.button7)
    Button button7;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TwoActivity.launch(MainActivity.this);
            }
        });
    }

    @OnClick({R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.button5, R.id.button6})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button1:
                //增加
                addUserData();
                break;
            case R.id.button2:
                //修改
                updateUserData();
                break;
            case R.id.button3:
                //删除
                deleteUserData();
                break;
            case R.id.button4:
                //全部查询
                queryListData();
                break;
            case R.id.button5:
                //按条件查询
                break;
            case R.id.button6:
                //sql 语句查询
                break;
            default:

        }
    }


    /**
     * 插入数据
     */
    public void addUserData() {

        User u1 = new User("zhy", "2B青年");
        DaoUtils.insertData(u1);
        u1 = new User("zhy2", "2B青年");
        DaoUtils.insertData(u1);
        u1 = new User("zhy3", "2B青年");
        DaoUtils.insertData(u1);
        u1 = new User("zhy4", "2B青年");
        DaoUtils.insertData(u1);
        u1 = new User("zhy5", "2B青年");
        DaoUtils.insertData(u1);
        u1 = new User("zhy6", "2B青年");
        DaoUtils.insertData(u1);


    }


    /**
     * 删除数据
     */
    public void deleteUserData() {
        User user = new User();
        user.setId(2);
        DaoUtils.deleteByDbBean(user);
    }

    /**
     * 更新数据
     */
    public void updateUserData() {
        User u1 = new User("zhy-android", "2B青年");
        u1.setId(3);
        DaoUtils.updateData(u1);


    }


    /**
     * 查询数据
     */
    public void queryListData() {
        User user = new User();
        List dbBeans = DaoUtils.queryData(user);
        if (dbBeans != null) {
            Log.d("LUO", "=======" + dbBeans.size());
            tv1.setText(dbBeans.toString() + "=====" + dbBeans.size());
        } else {
            tv1.setText("0");
        }


    }


}

ORMLITE 使用:

onCreate 初始化数据库

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

onUpgrade 升级数据库

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

注解含义

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

常用参数

  • 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

参考博客:
作者:EdwardWinner
链接:https://www.jianshu.com/p/a8a6429ac772
作者:鸿洋_
链接:https://blog.csdn.net/lmj623565791/article/details/39121377
作者:南鹏飞
链接:https://www.jianshu.com/p/c80fe4e8cd28
作者:CHX_W
链接:https://blog.csdn.net/CHX_W/article/details/78605213

你可能感兴趣的:(Android 中ORMLite 框架简单封装)