在Android中编写数据库CRUD操作的更有效方法

时间:2017-08-02 10:54:46

标签: java android crud dao

我刚刚开始学习Android开发,我发现了一种在我的应用程序中编写模型,DAO和模式的非常好的方法。例如,我有一个Category模型,它将包含表示数据库中其表的列的所有字段:

public class Category {
    private int id;
    private String name;
    private String createdAt;

    // Getters and Setters
}

CategoryDao类将响应访问数据库并执行所有操作:

package com.prettypenny.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.prettypenny.model.Category;
import com.prettypenny.schema.CategorySchema;
import com.prettypenny.schema.DatabaseHandler;

import java.util.ArrayList;

/**
 * Category D.A.O
 */
public class CategoryDao {
    SQLiteOpenHelper helper;
    SQLiteDatabase database;

    private static final String[] columns = {
        CategorySchema.COL_ID,
        CategorySchema.COL_NAME,
        CategorySchema.COL_CREATED_AT,
    };

    public CategoryDao(Context context) {
        helper = new DatabaseHandler(context);
    }

    public void open() {
        database = helper.getWritableDatabase();
    }

    public void close() {
        helper.close();
    }

    /**
     * Retrieve all Category
     * @return ArrayList
     */
    public ArrayList<Category> all() {
        Cursor cursor = database.query(CategorySchema.TABLE_NAME, columns, null, null, null, null, null);

        ArrayList<Category> categories = new ArrayList<>();

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Category category = new Category();
                category.setId(cursor.getInt(cursor.getColumnIndex(CategorySchema.COL_ID)));
                category.setName(cursor.getString(cursor.getColumnIndex(CategorySchema.COL_NAME)));

                categories.add(category);
            }
        }

        return categories;
    }

    /**
     * Inserts a new Category
     * @param category Category category to be inserted
     * @return Category
     */
    public Category insert(Category category) {
        ContentValues values = new ContentValues();
        values.put(CategorySchema.COL_NAME, category.getName());

        database.insert(CategorySchema.TABLE_NAME, null, values);

        return category;
    }

    /**
     * Updates an existing Category
     * @param category Category category to be updated
     * @return int
     */
    public int update(Category category) {
        ContentValues values = new ContentValues();
        values.put(CategorySchema.COL_NAME, category.getName());

        return database.update(
            CategorySchema.TABLE_NAME,
            values,
            CategorySchema.COL_ID + " = ?",
            new String[] { String.valueOf(category.getId()) }
        );
    }

    /**
     * Deletes an existing Category
     * @param id int id of the category to be deleted
     */
    public void delete(int id) {
        database.delete(
            CategorySchema.TABLE_NAME,
            CategorySchema.COL_ID + " = " + id,
            null
        );
    }
}

但是当我在我的应用程序中创建越来越多的实体时,我觉得必须输入所有这些相同的东西,所以我想要做一个抽象类Dao,它将具有所有这些操作,类将会只是扩展它。

abstract class Dao {
    SQLiteOpenHelper helper;
    SQLiteDatabase database;

    public ArrayList<?> all(String tableName, String[] columns) {
        Cursor cursor = database.query(tableName, columns, null, null, null, null, null);

        ArrayList<?> entities = new ArrayList<>();

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                // Oh shit.
            }
        }

        return entities;
    }
}

现在问题,例如,all()方法中的问题是要实例化的模型类,如CategoryDao.all()实例化Category。是否有可能在抽象类中实现,比如像ArrayList<?>那样做类似的东西,它传递的东西可能是任何类型的东西?

2 个答案:

答案 0 :(得分:2)

使用任何语言处理数据库时面临的最大挑战之一是数据库表和实体对象之间的关系映射。

考虑一下,创建了名为ORM(对象关系映射)的库/框架。

我的第一个建议是使用Realm Database,但由于您已经使用过SQLite,我的列表是:

可以找到它们之间的比较herehere

答案 1 :(得分:0)

我建议你看看谷歌的房间方法。它仍然不稳定,你需要android studio 3.0仍然不稳定,但我没有发现任何问题。

https://codelabs.developers.google.com/codelabs/android-persistence/#0

与典型的替代方案相比,它具有非常有趣的优势,其中之一是在编译时检查您的SQL语句是否与您的数据库匹配。我不知道有其他人提供这个特殊功能。