android 面向对象数据库编程

面向对象数据库编程

我们先看看操作示例

我们可以看到这里操作数据库只是引用了一个对象

        IBaseDao<Person> baseDao = BaseDaoFactory.getInstance().getBaseDao(Person.class);
        Person person = new Person();
        person.name = "熊大";
        person.setPassword(123456l);
        baseDao.insert(person);

从上面的操作示例我们可以看到
1.自动建表
2.面向对象插入

我们先看一下BaseDaoFactory.getInstance().getBaseDao(Person.class);
从这里面的代码我们可以看到 这里调用SQLiteDatabase.openOrCreateDatabase(sqlPath, null);创建了一个库
getBaseDao(Class<T> entityClass)里面创建了一个BaseDao实例调用了init方法进行了初始化

public class BaseDaoFactory {
    private static BaseDaoFactory ourInstance;
    private final SQLiteDatabase mSqLiteDatabase;

    public static BaseDaoFactory getInstance() {
        if (ourInstance == null) {
            ourInstance = new BaseDaoFactory();
        }
        return ourInstance;
    }

    private BaseDaoFactory() {
        String sqlPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/app.db";
        mSqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqlPath, null);

    }

    public synchronized <T>BaseDao getBaseDao(Class<T> entityClass) {
        BaseDao<T> baseDao = null;
        try {
            baseDao = BaseDao.class.newInstance();
            baseDao.init(entityClass,mSqLiteDatabase);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return  baseDao;

    }
}

紧接着我们看一下 baseDao.init(entityClass,mSqLiteDatabase);
这段代码我们可以看到 tableName = entityClass.getAnnotation(DBTable.class).value();
createTbale() 创建表的动作
这里获取了表明

    public synchronized void init(Class<T> entity, SQLiteDatabase sqLiteDatabase) {
        if (!isInit) {
            entityClass = entity;
            mSQLiteDatabase = sqLiteDatabase;
            tableName = entityClass.getAnnotation(DBTable.class).value();
            createTbale();
            initCacheMap();
            isInit = true;
        }
    }

上述代码我们看到 表名通过 获取实体类里的注解拿到的
那么我们看一下Person

我们可以看到@DBTable @DBFiled
@DBTable 表名 @DBFiled字段名

@DBTable("tb_person")
public class Person {


    @DBFiled("tb_name")
    public String name;
    @DBFiled("tb_password")
    public Long password;

    public String getName() {
        return name;
    }

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

    public Long getPassword() {
        return password;
    }

    public void setPassword(Long password) {
        this.password = password;
    }
}

@Target(ElementType.FIELD)//作用在成员变量上
@Retention(RetentionPolicy.RUNTIME)//运行时
public @interface DBFiled {
    String value();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
    String value();
}

上述代码我们看到了createTbale();创建表的一个操作我们看下是如何自动创建表的,我们看到是一个sql语句的拼接

    private void createTbale() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("create table if not exists ");
        stringBuilder.append(tableName);
        stringBuilder.append("(");
       //获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            Class type = field.getType();
            if (type == String.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " TEXT,");
            } else if (type == Double.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " DOUBLE,");
            } else if (type == Integer.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " INTEGER,");
            } else if (type == Float.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " FLOAT,");
            } else if (type == byte[].class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BLOB,");
            } else if (type == Long.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BIGINT,");
            } else {
                continue;
            }
        }
        if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        stringBuilder.append(")");
      
        this.mSQLiteDatabase.execSQL(stringBuilder.toString());

    }

剩下最后一步 通过对象插入数据 baseDao.insert(person); 遍历拿到字段名key, field.get(entity);拿到对应的属性

    @Override
    public void insert(T entity) {
        ContentValues contentValues = getValuse(entity);
        mSQLiteDatabase.insert(tableName, null, contentValues);
    }

    private ContentValues getValuse(T entity) {
        ContentValues contentValues = new ContentValues();
        Iterator<Map.Entry<String, Field>> iterator = cacheMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Field> fieldEntry = iterator.next();
            Field field = fieldEntry.getValue();
            //表的字段名
            String key = fieldEntry.getKey();

            field.setAccessible(true);
            try {
                Object object = field.get(entity);
                Class type = field.getType();
                if (type == String.class) {
                    String vlaue = (String) object;
                    contentValues.put(key, vlaue);
                } else if (type == Double.class) {
                    Double vlaue = (Double) object;
                    contentValues.put(key, vlaue);
                } else if (type == Integer.class) {
                    Integer vlaue = (Integer) object;
                    contentValues.put(key, vlaue);
                } else if (type == Float.class) {
                    Float vlaue = (Float) object;
                    contentValues.put(key, vlaue);
                } else if (type == byte[].class) {
                    byte[] vlaue = (byte[]) object;
                    contentValues.put(key, vlaue);
                } else if (type == Long.class) {
                    Long vlaue = (Long) object;
                    contentValues.put(key, vlaue);
                } else {
                    continue;
                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return contentValues;
    }

代码

Annotation
@Target(ElementType.FIELD)//作用在成员变量上
@Retention(RetentionPolicy.RUNTIME)//运行时
public @interface DBFiled {
    String value();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
    String value();
}



BaseDaoFactory

public class BaseDaoFactory {
    private static BaseDaoFactory ourInstance;
    private final SQLiteDatabase mSqLiteDatabase;

    public static BaseDaoFactory getInstance() {
        if (ourInstance == null) {
            ourInstance = new BaseDaoFactory();
        }
        return ourInstance;
    }

    private BaseDaoFactory() {
        String sqlPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/app.db";
        mSqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqlPath, null);

    }

    public synchronized <T>BaseDao getBaseDao(Class<T> entityClass) {
        BaseDao<T> baseDao = null;
        try {
            baseDao = BaseDao.class.newInstance();
            baseDao.init(entityClass,mSqLiteDatabase);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return  baseDao;

    }
}

BaseDao

public interface IBaseDao<T> {

   void insert(T entity);
   List<T> query(T where);
   void delte(T entity);
   void update(T oldEntity ,T newEntity);
}

public class BaseDao<T> implements IBaseDao<T> {
    /**
     * 持有数据操作引用
     */
    private SQLiteDatabase mSQLiteDatabase;
    /**
     * 操作的实体类
     */
    private Class<T> entityClass;

    /**
     * 表名
     */
    private String tableName;

    /**
     *缓存表的映射关系
     */
    private HashMap<String, Field> cacheMap;

    /**
     * 是否初始化
     */
    private boolean isInit = false;



    public synchronized void init(Class<T> entity, SQLiteDatabase sqLiteDatabase) {
        if (!isInit) {
            entityClass = entity;
            mSQLiteDatabase = sqLiteDatabase;
            tableName = entityClass.getAnnotation(DBTable.class).value();
            createTbale();
            initCacheMap();
            isInit = true;
        }
    }


    /**
     * 表的映射关系
     */
    private void initCacheMap() {
        cacheMap = new HashMap<>();
        String sql = "select  * from " + tableName + " limit 1,0";
        Cursor cursor = mSQLiteDatabase.rawQuery(sql, null);
        //获取表里面的字段名
        String[] columnNames = cursor.getColumnNames();
       // 获得该类的所有的公共(public)的字段,包括父类中的字段。
        Field[] columnFields = entityClass.getFields();

        for (String columnName : columnNames) {
            Field reslutField = null;
            for (Field field : columnFields) {
                if (columnName.equals(field.getAnnotation(DBFiled.class).value())) {
                    reslutField = field;
                    break;
                }
            }
            if (reslutField != null) {
                cacheMap.put(columnName, reslutField);
            }
        }
        cursor.close();

    }

    private static final String TAG = "BaseDao";

    private void createTbale() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("create table if not exists ");
        stringBuilder.append(tableName);
        stringBuilder.append("(");
       //获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            Class type = field.getType();
            if (type == String.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " TEXT,");
            } else if (type == Double.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " DOUBLE,");
            } else if (type == Integer.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " INTEGER,");
            } else if (type == Float.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " FLOAT,");
            } else if (type == byte[].class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BLOB,");
            } else if (type == Long.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BIGINT,");
            } else {
                continue;
            }
        }
        if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        stringBuilder.append(")");

        this.mSQLiteDatabase.execSQL(stringBuilder.toString());

    }


    private ContentValues getValuse(T entity) {
        ContentValues contentValues = new ContentValues();
        Iterator<Map.Entry<String, Field>> iterator = cacheMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Field> fieldEntry = iterator.next();
            Field field = fieldEntry.getValue();
            //表的字段名
            String key = fieldEntry.getKey();

            field.setAccessible(true);
            try {
                Object object = field.get(entity);
                Class type = field.getType();
                if (type == String.class) {
                    String vlaue = (String) object;
                    contentValues.put(key, vlaue);
                } else if (type == Double.class) {
                    Double vlaue = (Double) object;
                    contentValues.put(key, vlaue);
                } else if (type == Integer.class) {
                    Integer vlaue = (Integer) object;
                    contentValues.put(key, vlaue);
                } else if (type == Float.class) {
                    Float vlaue = (Float) object;
                    contentValues.put(key, vlaue);
                } else if (type == byte[].class) {
                    byte[] vlaue = (byte[]) object;
                    contentValues.put(key, vlaue);
                } else if (type == Long.class) {
                    Long vlaue = (Long) object;
                    contentValues.put(key, vlaue);
                } else {
                    continue;
                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return contentValues;
    }

    @Override
    public void insert(T entity) {
        ContentValues contentValues = getValuse(entity);
        mSQLiteDatabase.insert(tableName, null, contentValues);
    }

    @Override
    public List<T> query(T where) {
        List<T> list = new ArrayList<>();
        String condition = getCondition(where);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select * from ");
        stringBuffer.append(tableName);
        stringBuffer.append(" where ");
        stringBuffer.append(condition);
        Cursor cursor = mSQLiteDatabase.rawQuery(stringBuffer.toString(), null);
        while (cursor.moveToNext()) {
            try {
                T t = (T) where.getClass().newInstance();
                Field[] fields = t.getClass().getFields();
                String[] strings = cursor.getColumnNames();

                for (Field field : fields) {
                    String key = field.getAnnotation(DBFiled.class).value();
                    for (String string : strings) {
                        if (key.equals(string)) {
                            Class<?> type = field.getType();
                            if (type == String.class) {
                                field.set(t, cursor.getString(cursor.getColumnIndex(string)));
                            } else if (type == Double.class) {
                                field.set(t, cursor.getDouble(cursor.getColumnIndex(string)));
                            } else if (type == Integer.class) {
                                field.set(t, cursor.getInt(cursor.getColumnIndex(string)));
                            } else if (type == Float.class) {
                                field.set(t, cursor.getFloat(cursor.getColumnIndex(string)));
                            } else if (type == byte[].class) {
                                field.set(t, cursor.getBlob(cursor.getColumnIndex(string)));
                            } else if (type == Long.class) {
                                field.set(t, cursor.getLong(cursor.getColumnIndex(string)));
                            } else {
                                continue;
                            }
                        }
                    }

                }
                list.add(t);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        cursor.close();
        return list;
    }

    @Override
    public void delte(T entity) {
        String condition = getCondition(entity);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("delete from ");
        stringBuffer.append(tableName);
        stringBuffer.append(" where ");
        stringBuffer.append(condition);
        mSQLiteDatabase.execSQL(stringBuffer.toString());
    }

    /**
     * @param oldEntity 更新条件
     * @param newEntity 更新的字段
     * @return
     */
    @Override
    public void update(T oldEntity, T newEntity) {

        String old = getCondition(oldEntity);
        String n = getCondition(newEntity, " , ");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("update ");
        stringBuffer.append(tableName);
        stringBuffer.append(" set ");
        stringBuffer.append(n);
        stringBuffer.append(" where ");
        stringBuffer.append(old);
        Log.i(TAG, "update: " + stringBuffer.toString());
        mSQLiteDatabase.execSQL(stringBuffer.toString());
    }


    private String getCondition(T entity) {
        return getCondition(entity, " and ");
    }

    private String getCondition(T entity, String tag) {
        Iterator<Map.Entry<String, Field>> iterator = cacheMap.entrySet().iterator();
        StringBuffer stringBuffer = new StringBuffer();
        while (iterator.hasNext()) {
            Map.Entry<String, Field> fieldEntry = iterator.next();
            Field field = fieldEntry.getValue();
            //表的字段名
            String key = fieldEntry.getKey();
            try {
                Object object = field.get(entity);
                if (object != null) {
                    if (stringBuffer.length() > 0) {
                        stringBuffer.append(tag);
                    }
                    stringBuffer.append(key);
                    stringBuffer.append(" = ");
                    stringBuffer.append("'");
                    stringBuffer.append(object.toString());
                    stringBuffer.append("'");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }

}

Person 可以任意创建这里只是个演示bean

@DBTable("tb_person")
public class Person {


    @DBFiled("tb_name")
    public String name;
    @DBFiled("tb_password")
    public Long password;

    public String getName() {
        return name;
    }

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

    public Long getPassword() {
        return password;
    }

    public void setPassword(Long password) {
        this.password = password;
    }
}

实际操作

        final IBaseDao<Person> baseDao = BaseDaoFactory.getInstance().getBaseDao(Person.class);
        findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person person = new Person();
                person.name = name;
                person.setPassword(password++);
                baseDao.insert(person);
            }
        });

        findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person person = new Person();
                person.name = name;
                person.password = password++;
                baseDao.delte(person);
            }
        });
        findViewById(R.id.query).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person person = new Person();
                person.name = name;
                List<Person> list = baseDao.query(person);
                for (Person person1 : list) {
                    Log.i(TAG, "name= " + person1.name + " passowrd=" + person1.password);
                }
            }
        });

        findViewById(R.id.update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person old = new Person();
                old.name = name;
                old.password = 26l;
                Person n = new Person();
                n.name = "无敌";
                baseDao.update(old, n);
            }
        });

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,300评论 8 265
  • 我常常觉得家人对我的爱比我想象的还要谦卑。 我的奶奶听到我随口说的注意保暖的话,话筒那边就要抽鼻子。 我的妈妈保存...
    骞翮er阅读 256评论 0 1
  • 曾经路过你 便是到如今也无法走近你 任凭旁人添上无数模糊笔画 我还是喜欢那个纯白色的你啊 那个温柔浅笑的你啊 那个...
    阿火moete阅读 123评论 0 1