博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据库框架学习
阅读量:3749 次
发布时间:2019-05-22

本文共 6411 字,大约阅读时间需要 21 分钟。

这里写图片描述

/** * 抽象接口,定义增删改查等操作 * @param 
*/public interface IBaseDao
{ Long inserrt(T entity); int update(T entity, T where);}
/** * 用于通过对象的字段获取对应数据库的字段名称 */@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface DbFiled {
String value();}
/** * 用于获取表名 */@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DbTable {
String value();}
//对应表名称@DbTable("tb_user")public class User {
//对应表的字段名称 @DbFiled("name") public String name; @DbFiled("password") public String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
/** * 对应的表 */public class UserDao extends BaseDao {
@Override public String createDataBase() { return "create table if not exists tb_user(name varchar(20),password varchar(10))"; }}
/** * 核心类 * 实现了增删改查接口的方法 * 确立了表字段和表对象字段的对应关系 * @param 
*/public abstract class BaseDao
implements IBaseDao
{
private SQLiteDatabase sqLiteDatabase; private boolean isInit = false; private String tableName; private Class
entityClass; private Map
cacheMap = new HashMap();; public synchronized void init(Class
entity, SQLiteDatabase sqLiteDatabase) { if (!isInit) { this.sqLiteDatabase = sqLiteDatabase; this.tableName = entity.getAnnotation(DbTable.class).value(); this.entityClass = entity; sqLiteDatabase.execSQL(createDataBase()); initCacheMap(); } } /** * 找到数据库字段和表对象(User对象)对应的子段,创建Map */ protected void initCacheMap() { String sql = "select * from " + this.tableName + " limit 1,0"; Cursor cursor = null; try { cursor = this.sqLiteDatabase.rawQuery(sql, null); String[] columnNames = cursor.getColumnNames(); Field[] columnFields = entityClass.getFields(); for (Field field : columnFields) { field.setAccessible(true); } for (String columnName : columnNames) { for (Field field : columnFields) { String filedName; if (field.getAnnotation(DbFiled.class) != null) { filedName = field.getAnnotation(DbFiled.class).value(); } else { filedName = field.getName(); } if (columnName.equals(filedName)) { cacheMap.put(columnName, field); } } } } catch (Exception e) { } finally { cursor.close(); } } public abstract String createDataBase(); @Override public Long inserrt(T entity) { Map
map = getValues(entity); ContentValues contentvalues = getContentValues(map); Long result = sqLiteDatabase.insert(tableName, null, contentvalues); return result; } /** * 返回ContentValues * @param map key是数据库的字段名称,Value是需要插入的值 * @return ContentValues */ private ContentValues getContentValues(Map
map) { ContentValues contentvalues = new ContentValues(); Set keys = map.keySet(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = map.get(key); if (value != null) { contentvalues.put(key, value); } } return contentvalues; } /** * 将表对象的的field值取出,作为Value * 将field对象的数据库字段名取出,作为Key * @param entity 表对象(User) * @return Map */ public Map getValues(T entity) { HashMap
result = new HashMap<>(); Iterator fieldsIterator = cacheMap.values().iterator(); while (fieldsIterator.hasNext()) { Field colmunToFiled = (Field) fieldsIterator.next(); String cacheKey = null; String cacheValue = null; if (colmunToFiled.getAnnotation(DbFiled.class) != null) { cacheKey = colmunToFiled.getAnnotation(DbFiled.class).value(); } else { cacheKey = colmunToFiled.getName(); } try { if (null == colmunToFiled.get(entity)) { continue; } cacheValue = colmunToFiled.get(entity).toString(); } catch (Exception e) { e.printStackTrace(); } result.put(cacheKey, cacheValue); } return result; } @Override public int update(T entity, T where) { int result = -1; Map values = getValues(entity); Condition condition = new Condition(getValues(where)); result = sqLiteDatabase.update(tableName, getContentValues(values), condition.whereClauser, condition.WhereArgs); return result; }}
/** * 用于拼接查询语句 */public class Condition {
public String whereClauser; public String[] WhereArgs; public Condition(Map
map) { ArrayList list = new ArrayList(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(" 1=1 "); Set keys = map.keySet(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = map.get(key); if (null != value) { stringBuilder.append(" and " + key + " =? "); list.add(value); } } this.whereClauser = stringBuilder.toString(); this.WhereArgs = (String[]) list.toArray(new String[list.size()]); }}
public class MainActivity extends AppCompatActivity {
BaseDao baseDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); baseDao = DaoManagerFactory.instance().getDataHelper(UserDao.class, User.class); } public void insert(View view) { User user = new User(); user.setName("李四"); user.setPassword("123456"); baseDao.inserrt(user); }}
/** * 工厂类 */public class DaoManagerFactory {
private String path; private static DaoManagerFactory instance = new DaoManagerFactory(new File(Environment.getExternalStorageDirectory(), "ligic.db")); private SQLiteDatabase sqLiteDatabase; private DaoManagerFactory(File file) { this.path = file.getAbsolutePath(); openDataBase(); } private void openDataBase() { this.sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(path, null); } public synchronized
T getDataHelper(Class
clazz, Class
entityClass) {
//回过头细看 T baseDao = null; try { baseDao = clazz.newInstance(); baseDao.init(entityClass, sqLiteDatabase); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return baseDao; } public static DaoManagerFactory instance() { return instance; }}
你可能感兴趣的文章
SpringCloud Alibaba Nacos 服务注册和配置中心
查看>>
Vue 基础总结(2.x)
查看>>
poi读写Excel
查看>>
使用Security安全框架实现权限登录
查看>>
连接redis数据库工具类
查看>>
JDBC工具类 使用Durid连接池链接MySQL数据库
查看>>
ANSYS——模态提取方法简介
查看>>
ANSYS——模态分析的载荷施加问题以及约束的施加问题
查看>>
ANSYS——初学路径之路径的定义、作用以及ansys路径模块GUI的操作解释
查看>>
ANSYS——相同模型不同创建方式的同载荷同约束下的比较
查看>>
ANSYS——网格划分的不同方法以及GUI模块的操作(自由网格、映射网格、扫掠、拖拉)
查看>>
ANSYS——命令流学习(材料属性设置、建模的命令流)
查看>>
ANSYS——杆单元简介与示例(含新版本2019版本杆实常数设置、ANSYS help的使用、单元列表使用的举例)
查看>>
ANSYS——后处理中单元表(ELEMENT table)的作用、创建、使用
查看>>
在VScode上配置golang的开发环境
查看>>
LeetCode每日一题题解---乘积最大子数组
查看>>
leetcode每日一题---680. 验证回文字符串 Ⅱ
查看>>
leetcode每日一题---15. 三数之和
查看>>
leetcode每日一题--10. 正则表达式匹配
查看>>
leetcode每日一题---面试题 16.18. 模式匹配
查看>>