Sqlite 反射机制封装数据库

前端之家收集整理的这篇文章主要介绍了Sqlite 反射机制封装数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. public class sqliteDAO{
  2. static final String tag="DAO";
  3.  
  4. /**
  5. * 访问的数据库
  6. */
  7. private sqliteDatabase db;
  8.  
  9. /**
  10. * 数据库打开辅助类
  11. */
  12. private static PADoctorsqliteHelper paDoctorsqliteHelper;
  13. private static long curUserId;
  14.  
  15. /**
  16. * 数据插入冲突处理方式:
  17. * 0-忽略
  18. * 1-抛出异常
  19. * 2-替换数据
  20. */
  21. private int conflictType = 2;
  22.  
  23. public sqliteDAO(Context c,long userId){
  24. if (paDoctorsqliteHelper == null || userId != curUserId) {
  25. curUserId = userId;
  26. String prefix = "";
  27. try {
  28. prefix = c.getExternalFilesDir(null).getAbsolutePath() + "/";
  29. } catch (Exception e) {
  30. prefix = "";
  31. }
  32. paDoctorsqliteHelper = new PADoctorsqliteHelper(c,prefix+"u"+curUserId+".msg",null,1);
  33. }
  34. db = paDoctorsqliteHelper.getWritableDatabase();
  35. }
  36.  
  37. public void close() {
  38. //db.close();
  39. }
  40.  
  41. public sqliteDatabase getsqliteDatabase(){
  42. return db;
  43. }
  44.  
  45. /**
  46. * 插入对象到数据库,存储对象的所有字段到数据库的对应字段,包括NULL字段.
  47. * @param entity 待插入的对象
  48. * @return 如果插入数据库成功则返回该对象,否则返回NULL
  49. */
  50. public <T> T insert(T entity){
  51. return insert(entity,false);
  52. }
  53.  
  54. /**
  55. * 插入对象到数据库,仅存储对象的非空字段到数据库,对象的NULL字段将被忽略.
  56. * @param entity 待插入的对象
  57. * @return 如果插入数据库成功则返回该对象,否则返回NULL
  58. */
  59. public <T> T insertSelective(T entity){
  60. return insert(entity,true);
  61. }
  62.  
  63. private <T> T insert(T entity,boolean selective){
  64. ContentValues values=getContentValues(entity,selective);
  65.  
  66. // T exist_obj=this.loadByPrimaryKey(entity);
  67. // if(exist_obj!=null){
  68. // return exist_obj;
  69. // }
  70.  
  71. long r;
  72. if(conflictType == 2){
  73. r = db.replace(getTableName(entity),values);
  74. }else{
  75. r = db.insert(getTableName(entity),values);
  76. }
  77.  
  78. if(r >= 0){
  79. return entity;
  80. }
  81.  
  82. return null;
  83. }
  84.  
  85. /**
  86. * 根据主键删除数据
  87. * @param entity 待删除的对象,主键只必须设置.
  88. * @return
  89. */
  90. public <T> int delete(T entity){
  91. Object[] args=getPrimarySelectionAndArgs(entity);
  92. return db.delete(getTableName(entity),(String)args[0],(String[])args[1]);
  93. }
  94.  
  95. /**
  96. *
  97. * @param entity
  98. * @param whereClause
  99. * @param whereArgs
  100. * @return the number of rows affected if a whereClause is passed in,0 otherwise.
  101. * To remove all rows and get a count pass "1" as the whereClause.
  102. */
  103. public <T> int deleteByWhereClause(T entity,String whereClause,String[] whereArgs) {
  104. return db.delete(getTableName(entity),whereClause,whereArgs);
  105. }
  106.  
  107. /**
  108. * 根据主键从数据库载入一条记录到对象
  109. * @param entity 数据实体(必须初始化主键字段)
  110. * @return 成功则返回的该数据库实体,失败则返回NULL
  111. */
  112. public <T> T loadByPrimaryKey(T entity){
  113. Object[] args=getPrimarySelectionAndArgs(entity);
  114. Cursor cursor=db.query(getTableName(entity),(String[])args[1],null);
  115. try{
  116. if(cursor.moveToNext()){
  117. T db_entity=getEntity(cursor,entity);
  118. return db_entity;
  119. }else{
  120. return null;
  121. }
  122. }finally{
  123. cursor.close();
  124. }
  125. }
  126.  
  127. @SuppressWarnings("unchecked")
  128. public <T> List<T> query(T entity,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit){
  129. List<T> entities = new ArrayList<T>();
  130. Cursor cursor = db.query(getTableName(entity),columns,selection,selectionArgs,groupBy,having,orderBy,limit);
  131. try{
  132. if(cursor!=null && cursor.moveToFirst()){
  133. T obj=(T)entity.getClass().newInstance();
  134. getEntity(cursor,obj);
  135. entities.add(obj);
  136. while(cursor.moveToNext()) {
  137. obj=(T)entity.getClass().newInstance();
  138. getEntity(cursor,obj);
  139. entities.add(obj);
  140. }
  141. }
  142. return entities;
  143. }catch(Exception e){
  144. Log.e(tag,""+e,e);
  145. return entities;
  146. }finally{
  147. cursor.close();
  148. }
  149. }
  150.  
  151. @SuppressWarnings("unchecked")
  152. public <T> List<T> loadAll(T entity,String limit){
  153. List<T> entities=new ArrayList<T>();
  154.  
  155. Cursor cursor=db.query(getTableName(entity),e);
  156. return entities;
  157. }finally{
  158. cursor.close();
  159. }
  160. }
  161.  
  162. /**
  163. * 更新数据库实体,更新对象的所有字段到数据库的对应字段,包括NULL字段.
  164. * @param entity 待更新的对象(必须包含主键)
  165. * @return 成功更新的记录数
  166. */
  167. public int updateByPrimaryKey(Object entity){
  168. return updateByPrimaryKey(entity,false);
  169. }
  170.  
  171. /**
  172. * 更新数据库实体,仅更新对象的非空字段到数据库的对应字段,对象的NULL字段将被忽略.
  173. * @param entity 待更新的对象(必须包含主键)
  174. * @return 成功更新的记录数
  175. */
  176. public int updateByPrimaryKeySelective(Object entity){
  177. return updateByPrimaryKey(entity,true);
  178. }
  179.  
  180. private int updateByPrimaryKey(Object entity,selective);
  181. Object[] args=getPrimarySelectionAndArgs(entity);
  182.  
  183. int r=db.update(getTableName(entity),values,(String[])args[1]);
  184.  
  185. return r;
  186. }
  187.  
  188. /**
  189. * 从对象中解析出主键字段,以及主键字段对应的值
  190. * @param entity
  191. * @return
  192. */
  193. private Object[] getPrimarySelectionAndArgs(Object entity){
  194. Object[] ret=new Object[2];
  195. String selection=null;
  196. List<String> args=new ArrayList<String>();
  197. try{
  198. Class<?> entity_class=entity.getClass();
  199. Field[] fs=entity_class.getDeclaredFields();
  200. for(Field f:fs){
  201. if(isPrimaryKey(f)){
  202. Method get=getGetMethod(entity_class,f);
  203. if(get!=null){
  204. Object o=get.invoke(entity);
  205. String value=null;
  206. if(o!=null){
  207. value=o.toString();
  208. if(selection==null){
  209. selection=f.getName()+"=?";
  210. }else{
  211. selection+=" AND "+f.getName()+"=?";
  212. }
  213.  
  214. args.add(value);
  215.  
  216. }else{
  217. throw new RuntimeException("Primary key: "+f.getName()+" must not be null");
  218. }
  219. }
  220. }
  221. }
  222. if(selection==null){
  223. throw new RuntimeException("Primary key not found!");
  224. }
  225.  
  226. ret[0]=selection;
  227. ret[1]=args.toArray(new String[args.size()]);
  228. return ret;
  229. }catch(Exception e){
  230. throw new RuntimeException(e.getMessage(),e);
  231. }
  232. }
  233.  
  234. /**
  235. * 将对象转换为ContentValues
  236. * @param entity
  237. * @param selective
  238. * @return
  239. */
  240. private ContentValues getContentValues(Object entity,boolean selective){
  241. ContentValues values=new ContentValues();
  242. try{
  243. Class<?> entity_class=entity.getClass();
  244. Field[] fs=entity_class.getDeclaredFields();
  245. for(Field f:fs){
  246. if(isTransient(f)==false){
  247. Method get=getGetMethod(entity_class,f);
  248. if(get!=null){
  249. Object o=get.invoke(entity);
  250. if(!selective || (selective && o!=null)){
  251. String name=f.getName();
  252. Class<?> type=f.getType();
  253. if(type==String.class){
  254. values.put(name,(String)o);
  255. }else if(type==int.class || type==Integer.class){
  256. values.put(name,(Integer)o);
  257. }else if(type==float.class || type==Float.class){
  258. values.put(name,(Float)o);
  259. }else if(type==long.class || type==Long.class){
  260. values.put(name,(Long)o);
  261. }else if(type==Date.class){
  262. values.put(name,datetimeToString((Date)o));
  263. }else{
  264. values.put(name,o.toString());
  265. }
  266. }
  267. }
  268. }
  269. }
  270. return values;
  271. }catch(Exception e){
  272. throw new RuntimeException(e.getMessage(),e);
  273. }
  274. }
  275.  
  276. /**
  277. * 将数据库记录转换为对象
  278. *
  279. * @param cursor
  280. * @param entity
  281. * @return
  282. */
  283. private <T> T getEntity(Cursor cursor,T entity){
  284. try{
  285. Class<?> entity_class=entity.getClass();
  286.  
  287. Field[] fs=entity_class.getDeclaredFields();
  288. for(Field f:fs){
  289. int index=cursor.getColumnIndex(f.getName());
  290. if(index>=0){
  291. Method set=getSetMethod(entity_class,f);
  292. if(set!=null){
  293. String value=cursor.getString(index);
  294. if(cursor.isNull(index)){
  295. value=null;
  296. }
  297. Class<?> type=f.getType();
  298. if(type==String.class){
  299. set.invoke(entity,value);
  300. }else if(type==int.class || type==Integer.class){
  301. set.invoke(entity,value==null?(Integer)null:Integer.parseInt(value));
  302. }else if(type==float.class || type==Float.class){
  303. set.invoke(entity,value==null?(Float)null:Float.parseFloat(value));
  304. }else if(type==long.class || type==Long.class){
  305. set.invoke(entity,value==null?(Long)null:Long.parseLong(value));
  306. }else if(type==Date.class){
  307. set.invoke(entity,value==null?(Date)null:stringToDateTime(value));
  308. }else{
  309. set.invoke(entity,value);
  310. }
  311. }
  312. }
  313. }
  314. return entity;
  315. }catch(Exception e){
  316. throw new RuntimeException(e.getMessage(),e);
  317. }
  318. }
  319.  
  320. private String datetimeToString(Date d){
  321. SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  322. if(d!=null){
  323. return sdf.format(d);
  324. }
  325. return null;
  326. }
  327.  
  328. private Date stringToDateTime(String s){
  329. SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  330. if(s!=null){
  331. try {
  332. return sdf.parse(s);
  333. } catch (ParseException e) {
  334. Log.e(tag,"解析时间错误: "+s,e);
  335. }
  336. }
  337. return null;
  338. }
  339.  
  340. private Method getGetMethod(Class<?> entity_class,Field f){
  341. String fn=f.getName();
  342. String mn="get"+fn.substring(0,1).toUpperCase()+fn.substring(1);
  343. try{
  344. return entity_class.getDeclaredMethod(mn);
  345. }catch(NoSuchMethodException e){
  346. Log.w(tag,"Method: "+mn+" not found.");
  347.  
  348. return null;
  349. }
  350. }
  351.  
  352. private Method getSetMethod(Class<?> entity_class,Field f){
  353. String fn=f.getName();
  354. String mn="set"+fn.substring(0,1).toUpperCase()+fn.substring(1);
  355. try{
  356. return entity_class.getDeclaredMethod(mn,f.getType());
  357. }catch(NoSuchMethodException e){
  358. Log.w(tag,"Method: "+mn+" not found.");
  359.  
  360. return null;
  361. }
  362. }
  363.  
  364. /**
  365. * 检查是否为主键字段
  366. */
  367. private boolean isPrimaryKey(Field f){
  368. Annotation an=f.getAnnotation(Id.class);
  369. if(an!=null){
  370. return true;
  371. }
  372. return false;
  373. }
  374.  
  375. private boolean isTransient(Field f){
  376. Annotation an=f.getAnnotation(Transient.class);
  377. if(an!=null){
  378. return true;
  379. }
  380. return false;
  381. }
  382.  
  383. private String getTableName(Object entity){
  384. Table table=entity.getClass().getAnnotation(Table.class);
  385. String name= table.name();
  386. return name;
  387. }
  388.  
  389. public int getConflictType() {
  390. return conflictType;
  391. }
  392.  
  393. public void setConflictType(int conflictType) {
  394. this.conflictType = conflictType;
  395. }
  396.  
  397. }

猜你在找的Sqlite相关文章