preface

SqliteopenHelper is often used in the project to implement the database add, delete, change and search, but it is very cumbersome to use, need to write a lot of long-winded code. So the design of object-oriented database framework is the way to solve the above problems.

OOP database design UML class diagram

Role:
  • BaseDaoFactory: Used to create and initialize databases
  • IBaseDao: add, delete, modify, and check methods interface
  • BaseDao: an abstract template class that implements subclass UserDao.
  • Beans: Use annotations to define related field names and types in a table, such as UserBean
  • ConcreteDao: Create a table, specifying fields and their lengths, corresponding to fields in the UserBean (UserDao)
  • Client: Calls a class, such as an Activity

2. Implementation of each role

BaseDaoFactory:

public class BaseDaoFactory {

    private static BaseDaoFactory instance = new BaseDaoFactory();

    private String sqliteDatabasePath;

    private SQLiteDatabase sqLiteDatabase;

    public BaseDaoFactory(a) {
        sqliteDatabasePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/teacher.db";
        openDatabase();
    }

    public static BaseDaoFactory getInstance(a) {
        return instance;
    }

    public synchronized <T extends BaseDao<M>, M> T getDataHelper(Class<T> clazz, Class<M> entityClass) {
        BaseDao baseDao = null;
        try {
            baseDao = clazz.newInstance();
            baseDao.init(entityClass, sqLiteDatabase);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) baseDao;
    }
    /** * If targetSdkVersion is greater than 22, request read/write permission for the storage */
    // Open the database operation
    private void openDatabase(a) {

        this.sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqliteDatabasePath, null); }}Copy the code
IBaseDao:

public interface IBaseDao<T>{
    / * * *@param entity
     * @return* /
    Long insert(T entity);

    /** * Update data *@param entity
     * @param where
     * @return* /
    int update(T entity,T where);

    /** * delete data *@param where
     * @return* /
    int delete(T where);

    List<T> query(T where);

    List<T> query(T where,String orderBy,Integer startIndex,Integer limit);
}
Copy the code
BaseDao:

/** * Created by Xionghu on 2018/2/2. * Desc: Actually dealing with the bottom layer **@param <T>
 */

public abstract class BaseDao<T> implements IBaseDao<T> {

    /** * holds a reference to the database action class */
    private SQLiteDatabase database;

    /** ** ensure instantiation once */
    private boolean isInit = false;

    /** * holds the Java type * User */ corresponding to the operation data table
    private Class<T> entityClass;

    / * * * to maintain the name of the table with the member variable name * key mapping relations -- -- -- - > value -- -- -- -- > table name * Field * /
    private HashMap<String, Field> cacheMap;

    private String tableName;

    / * * *@param entity
     * @param sqLiteDatabase
     * @returnInstantiate once */
    protected synchronized boolean init(Class<T> entity, SQLiteDatabase sqLiteDatabase) {
        if(! isInit) { entityClass = entity; Log.d("sqlite", entityClass.getSimpleName());
            database = sqLiteDatabase;
            if (entity.getAnnotation(DbTable.class) == null) {
                tableName = entity.getClass().getSimpleName();
            } else {
                tableName = entity.getAnnotation(DbTable.class).value();
            }
            if(! database.isOpen()) {return false;
            }
            if(! TextUtils.isEmpty(createTable())) { database.execSQL(createTable()); } cacheMap =new HashMap<>();
            initCacheMap();
            isInit = true;
        }
        return isInit;
    }

    /** * Maintain the mapping */
    private void initCacheMap(a) {
        String sql = "select * from " + this.tableName + " limit 1 , 0 ";
        Cursor cursor = null;
        try {

            cursor = database.rawQuery(sql, null);
            /** * array of column names */
            String[] columnNames = cursor.getColumnNames();
            /** * get the Field array */
            Field[] colmunFields = entityClass.getFields();
            for (Field field : colmunFields) {
                field.setAccessible(true);
            }
            /** ** start to find the corresponding */
            for (String colmunName : columnNames) {
                /** ** field = User */
                Field colmunFiled = null;
                for (Field field : colmunFields) {
                    String fileName = null;
                    if(field.getAnnotation(DbFiled.class) ! =null) {
                        fileName = field.getAnnotation(DbFiled.class).value();
                    } else {
                        fileName = field.getName();
                    }
                    /** * if the table name is equal to the annotation name of the member variable */
                    if (colmunName.equals(fileName)) {
                        colmunFiled = field;
                        break; }}// Find the corresponding relationship
                if(colmunFiled ! =null) { cacheMap.put(colmunName, colmunFiled); }}}catch (Exception e) {
            e.printStackTrace();
        } finally{ cursor.close(); }}@Override
    public Long insert(T entity) {
        Map<String, String> map = getValues(entity);
        ContentValues values = getContentValues(map);
        Long result = database.insert(tableName, null, values);
        return result;
    }

    / * * *@param entity
     * @param where
     * @return* /
    @Override
    public int update(T entity, T where) {
        int result = -1;
        Map values = getValues(entity);

        /** * conditional object conversion map */
        Map whereClause = getValues(where);
        Condition condition = new Condition(whereClause);
        ContentValues contentValues = getContentValues(values);
        result = database.update(tableName, contentValues, condition.getWhereClause(), condition.getWhereArgs());

        return result;
    }

    @Override
    public int delete(T where) {
        Map map = getValues(where);
        Condition condition = new Condition(map);

        /** * id=1 new String[]{ String.value(1)} */
        int result = database.delete(tableName, condition.getWhereClause(), condition.getWhereArgs());
        return result;
    }

    // Query all data
    @Override
    public List<T> query(T where) {
        return query(where, null.null.null);
    }

    @Override
    public List<T> query(T where, String orderBy, Integer startIndex, Integer limit) {
        Map map = getValues(where);
        String limitString = null;
        if(startIndex ! =null&& limit ! =null) {
            limitString = startIndex + "," + limit;
        }
        Condition condition = new Condition(map);
        Cursor cursor = database.query(tableName, null, condition.getWhereClause(), condition.getWhereArgs(),
                null.null, orderBy, limitString);
        List<T> result = getResult(cursor, where);
        cursor.close();
        return result;
    }


    private List<T> getResult(Cursor cursor, T where) {
        ArrayList list = new ArrayList();
        Object item;
        while (cursor.moveToNext()) {
            try {
                item = where.getClass().newInstance();
                /** * column name * Member variable name Filed */
                Iterator iterator = cacheMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    /** * get the column name */
                    String colomunName = (String) entry.getKey();
                    /** * then get the column name in the cursor position */
                    Integer colmunIndex = cursor.getColumnIndex(colomunName);

                    Field field = (Field) entry.getValue();
                    Class type = field.getType();
                    if(colmunIndex ! = -1) {
                        if (type == String.class) {
                            // Reflection mode assignment
                            field.set(item, cursor.getString(colmunIndex));
                        } else if (type == Double.class) {
                            field.set(item, cursor.getDouble(colmunIndex));
                        } else if (type == Integer.class) {
                            field.set(item, cursor.getInt(colmunIndex));
                        } else if (type == Long.class) {
                            field.set(item, cursor.getLong(colmunIndex));
                        } else if (type == Float.class) {
                            field.set(item, cursor.getFloat(colmunIndex));
                        } else if (type == byte[].class) {
                            field.set(item, cursor.getBlob(colmunIndex));
                        } else {
                            continue;
                        }

                    }


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

    /** * convert to ContentValues **@param map
     * @return* /
    private ContentValues getContentValues(Map<String, String> map) {
        ContentValues contentValues = new ContentValues();
        Set keys = map.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = map.get(key);
            if(value ! =null) { contentValues.put(key, value); }}return contentValues;
    }


    private Map<String, String> getValues(T entity) {
        HashMap<String, String> result = new HashMap<>();
        Iterator<Field> fieldsIterator = cacheMap.values().iterator();
        /** * loop over the map's Field */
        while (fieldsIterator.hasNext()) {
            Field columnToField = fieldsIterator.next();
            String cacheKey = null;
            String cacheValue = null;
            if(columnToField.getAnnotation(DbFiled.class) ! =null) {
                cacheKey = columnToField.getAnnotation(DbFiled.class).value();
            } else {
                cacheKey = columnToField.getName();
            }
            try {
                if (null == columnToField.get(entity)) {
                    continue;
                }
                cacheValue = columnToField.get(entity).toString();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            result.put(cacheKey, cacheValue);
        }
        return result;
    }


    /** * create table **@return* /
    protected abstract String createTable(a);

    /** * encapsulates the change statement */
    class Condition {


        /** * name=? && password = ? * /
        private String whereClause;

        private String[] whereArgs;


        public Condition(Map<String, String> whereClause) {
            ArrayList list = new ArrayList();
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.append(" 1=1 ");

            Set keys = whereClause.keySet();
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                String value = whereClause.get(key);

                if(value ! =null) {
                    * 1=1 and name =? and password = ? * /
                    stringBuilder.append(" and " + key + "=?"); list.add(value); }}this.whereClause = stringBuilder.toString();
            this.whereArgs = (String[]) list.toArray(new String[list.size()]);
        }

        public String getWhereClause(a) {
            return whereClause;
        }

        public void setWhereClause(String whereClause) {
            this.whereClause = whereClause;
        }

        public String[] getWhereArgs() {
            return whereArgs;
        }

        public void setWhereArgs(String[] whereArgs) {
            this.whereArgs = whereArgs; }}}Copy the code
Bean:

@DbTable("tb_user")
public class User {

    /** * public Integer userId; * The data is saved in the field named userId * note: *@DbFiled("teacher_id") * public Integer userId; Teacher_id = teacher_id = teacher_id = teacher_id = teacher_id = teacher_id
    public Integer userId;

    @DbFiled("name")
    public String name;
    @DbFiled("password")
    public String password;

    public User(Integer userId, String name, String password) {
        this.userId = userId;
        this.name = name;
        this.password = password;
    }

    public User(a) {}public Integer getUserId(a) {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getName(a) {
        return name;
    }

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

    public String getPassword(a) {
        return password;
    }

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

    @Override
    public String toString(a) {
        return "User{" +
                "userId=" + userId +
                ", name='" + name + ' '' + ", password='" + password + ''' + '}'; }}Copy the code

@Target(ElementType.FIELD) // Constants for fields and enumerations
@Retention(RetentionPolicy.RUNTIME) // Annotations exist in the class bytecode file and can be retrieved at runtime
public @interface DbFiled {
    String value(a);
}
Copy the code

@Target(ElementType.TYPE) // applies to interfaces, class enumerations, annotations
@Retention(RetentionPolicy.RUNTIME) // Annotations exist in the class bytecode file and can be retrieved at runtime
public @interface DbTable {
    String value(a);
}
Copy the code
ConcreteDao:

public class UserDao extends BaseDao {

    @Override
    protected String createTable(a) {
        return "create table if not exists tb_user(userId int,name varchar(20),password varchar(20))"; }}Copy the code

public class FileDao extends BaseDao {
    @Override
    protected String createTable(a) {
        return "create table if not exists tb_file(time varchar(20),path varchar(20),description varchar(20))"; }}Copy the code
Client:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Main";
    IBaseDao<User> baseDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); baseDao = BaseDaoFactory.getInstance().getDataHelper(UserDao.class, User.class); }}Copy the code

3. Add, delete, change, check and test

Step1: add

    public void save(View view) {

        for (int i = 0; i < 20; i++) {
            User user = new User(i, "teacher"."123456");
            baseDao.insert(user);
        }

/** * Writes file data */
// BaseDao
      
        fileBeanBaseDao = BaseDaoFactory.getInstance().getDataHelper(FileDao.class, FileBean.class);
      
// fileBeanBaseDao.insert(new FileBean("2019-12-13", Environment.getExternalStorageDirectory() + "/kpioneer", "asdfg"));

    }
Copy the code

Execute queryAll to print the data


02-06 17:51:06.151 4858-4858/com.haocai.haocaisqlite I/Main: Found20The data02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=0, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=1, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=2, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=3, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=4, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=5, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=6, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=7, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=8, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=9, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=10, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=11, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=12, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=13, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=14, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=15, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=16, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=17, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=18, name='teacher', password='123456'}
02-06 17:51:06.152 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=19, name='teacher', password='123456'}
Copy the code
Step2: change

    public void update(View view) {
        for (int i = 10; i < 20; i++) {
            User where = new User();
            where.setUserId(i);
            User user = new User(i, "kpioneer"."8888");

            Name = teacherbaseDao.update(user, where); }}Copy the code

Execute queryAll to print the data


02-06 17:54:18.650 4858-4858/com.haocai.haocaisqlite I/Main: Found20The data02-06 17:54:18.650 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=0, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=1, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=2, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=3, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=4, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=5, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=6, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=7, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=8, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=9, name='teacher', password='123456'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=10, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=11, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=12, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=13, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=14, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=15, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=16, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=17, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=18, name='kpioneer', password='8888'}
02-06 17:54:18.651 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=19, name='kpioneer', password='8888'}
Copy the code
Step3: check

    public void query(View view) {
        User where = new User();
        where.setName("teacher");
        List<User> list = baseDao.query(where);

        Log.i(TAG, "Found" + list.size() + "Piece of data");
        for (User user : list) {
            Log.i(TAG, user.toString());
        }

        System.out.println("-------- Query some data -------");
        User where2 = new User();
        where2.setName("teacher");
        where2.setUserId(5);
        List<User> list2 = baseDao.query(where2);
        Log.i(TAG, "Found" + list2.size() + "Piece of data");
    }
Copy the code

Print data


02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: Found10The data02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=0, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=1, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=2, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=3, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=4, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=5, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=6, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=7, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=8, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=9, name='teacher', password='123456'}
02-06 17:58:49.530 4858-4858/ com. Haocai. Haocaisqlite I/System. Out: -- -- -- -- -- -- -- -- a query for a data -- -- -- -- -- -- --02-06 17:58:49.533 4858-4858/com.haocai.haocaisqlite I/Main: Found1The dataCopy the code
Step4: delete

    public void delete(View view) {
        User user = new User();
        user.setName("teacher");
        baseDao.delete(user);
    }
Copy the code

Execute queryAll to print the data


02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: Found10The data02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=10, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=11, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=12, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=13, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=14, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=15, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=16, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=17, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=18, name='kpioneer', password='8888'}
02-06 18:00:29.196 4858-4858/com.haocai.haocaisqlite I/Main: User{userId=19, name='kpioneer', password='8888'}
Copy the code
At this point, the object-oriented database architecture design is complete.