首页 > 系统 > Android > 正文

android手把手教你写数据库框架(第二篇)

2019-11-09 13:48:12
字体:
来源:转载
供稿:网友

上一篇讲了框架的基本结构,第一篇是关键,后期都是做些数据的业务处理了,比如增删改查的,针对上一篇自动建表是有bug的在studio2.0使用反射会多出2个属性,一个是$change,一个是SerializableId什么的,具体的忘记了,是这个导致bug产生的,因为我们在在自动创建表的时候是利用反射去读取实体bean的属性,然后利用属性上的注解,进行建表的操作,之间建表的代码入下:

String tb_name =  User.class.getAnnotation(AnnTableName.class).value();        Field[] fields =  User.class.getDeclaredFields();        String fieldName = "";        String type = "";        int len = 0;        Map<String,Field> columsMap = new HashMap<>();        for(Field field:fields){            columsMap.put(field.getName(),field);        }        StringBuffer sb = new StringBuffer(Constant.create_table_PRix);        sb.append(" ");        sb.append(tb_name);        boolean isFirst = false;        int i=0;        for (Map.Entry<String, Field> entry: columsMap.entrySet()) {            Field filed = entry.getValue();            if(!isFirst){                isFirst = true;                sb.append("(");            }            if(filed.getAnnotation(AnnFiled.class)!=null){                fieldName=filed.getAnnotation(AnnFiled.class).columnName();                type = filed.getAnnotation(AnnFiled.class).type();                len = filed.getAnnotation(AnnFiled.class).len();                sb.append(fieldName).append(" ").append(type).append(len>0?"("+len+")":"").append((i==columsMap.size()-1)? ")":",");                i++;            }        }bug发生在这行代码上:
sb.append(fieldName).append(" ").append(type).append(len>0?"("+len+")":"").append((i==columsMap.size()-1)? ")":",");比如我们写的User实体有三个属性,但是反射出来后多了2个,那么columnsMap集合size就是5了,但是我们是做了判断,判断这个属性是否有注解,昨天晚上对这个bug进行了修复,整个UserDao就是一个功能就是自动建表,代码入下:
package com.sqlite.dao;import android.text.TextUtils;import com.sqlite.annotation.AnnFiled;import com.sqlite.annotation.AnnTableName;import com.sqlite.bean.User;import com.sqlite.constant.Constant;import com.sqlite.dao.base.BaseDao;import com.sqlite.utils.LogUtils;import java.lang.reflect.Field;import java.util.HashMap;import java.util.Map;/** * Created by admin on 2017/2/6. */public class UserDao extends BaseDao<User> {    @Override    protected String createTable(User user) {        String tb_name =  User.class.getAnnotation(AnnTableName.class).value();        Field[] fields =  User.class.getDeclaredFields();        Map<String,Field> columsMap = new HashMap<>();        for(Field field:fields){            columsMap.put(field.getName(),field);        }        Map<String,Field> cacheColumsMap = checkAnnotationValue(columsMap);        return dynamicCreateTable(tb_name,cacheColumsMap);    }    /**     * 创建表     */    private String dynamicCreateTable(String tb_name,Map<String,Field> cacheColumsMap) {        String table = "";        if(TextUtils.isEmpty(tb_name)||cacheColumsMap==null||cacheColumsMap.isEmpty()){            return table;        }        String fieldName = "";        String type = "";        int len = 0;        StringBuffer sb = new StringBuffer(Constant.create_table_prix);        sb.append(" ");        sb.append(tb_name);        boolean isFirst = false;        int i=0;        for (Map.Entry<String, Field> entry: cacheColumsMap.entrySet()) {            Field filed = entry.getValue();            if(!isFirst){                isFirst = true;                sb.append("(");            }            if(filed.getAnnotation(AnnFiled.class)!=null){                fieldName=filed.getAnnotation(AnnFiled.class).columnName();                type = filed.getAnnotation(AnnFiled.class).type();                len = filed.getAnnotation(AnnFiled.class).len();                sb.append(fieldName).append(" ").append(type).append(len>0?"("+len+")":"").append((i==cacheColumsMap.size()-1)? ")":",");                i++;            }        }        table = sb.toString();        return table;    }    private Map<String,Field> checkAnnotationValue(Map<String, Field> columsMap) {        Map<String,Field> cacheColumsMap = new HashMap<>();        if(columsMap!=null&&!columsMap.isEmpty()){            for (Map.Entry<String, Field> entry: columsMap.entrySet()) {                Field filed = entry.getValue();                if(filed.getAnnotation(AnnFiled.class)!=null){                    cacheColumsMap.put(filed.getName(),filed);                }            }        }        return cacheColumsMap;    }}就是先判断这个属性是否有注解,临时用一个容器去存储在属性上注解的,然后再进行遍历,拼写sql语句.这个bug修复了,就接着今天的内容吧,上篇就讲了一个数据的插入,而且是插入单个记录,

@Overridepublic Long insert(T entity) {    Map<String,String> map=getValues(entity);    ContentValues values=getContentValues(map);    Long result =dataBase.insert(tbName,null,values);    return result;}那么插入多条记录,也是很简单的,首先在IBaseDao接口中声明一个方法:

Long insert(List<T> entity);我们把IBaseDao定义成了一个接口,就是对数据库的增删改查做了一个抽取或者定了对其规则,真正的实现逻辑都是封装在BaseDao,看类名就知道是对数据库进行增删改查的,多条记录插入:

@Overridepublic Long insert(List<T> entity) {    Long result = 0l;    if(entity!=null&&!entity.isEmpty()){        for(T t:entity){            result =  insert(t);        }    }    return result;}现在我把之前的数据移除,重新创建,然后插入多条数据:

private void addMultipleData() {    List<User> users = new ArrayList<>();    for(int i=0;i<20;i++){        User user = new User();        user.setAge(18+i);        user.setName("zhouguizhi"+i);        user.setPassWord("123456");        users.add(user);    }    baseDao.insert(users);}插入后再把user.db文件导入到SQLite Expert文件打开查看刚才插入的数据是否插入成功.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表