365bet亚洲版登录-bet官网365入口

365bet亚洲版登录拥有超过百间客房,bet官网365入口的文化历经几十年的传承和积淀形成的核心内容获得业界广泛的认可,365bet亚洲版登录是目前信誉最高的娱乐场所,同国内外几百家网上内容供应商建立了合作关系。

写一个简单的Android版本的ORM

几年前刚刚提到做Android开拓时候到底头大的是数据库相关的增加和删除改查,因为品种要对离线数据举办政管理制数据库操作相当多,不断通过查询Cursor拼装成对象,完了还要close cursor,重复专门的学问太多太累,曾经用过Hibernate只是Android平台未有罢了,那一刻也还未有Android平台的权威级的ORM。经过项目实行有意或无意做了二个之类操作DB的小lib,简化了广大双重劳动.

开始的一段时代的发芽来自于Android Email App内部二个叫EmailContent的class定义。每一个Table类都手动完结toContentValues()和restore(Cursor cursor),那样可以制止再度通过Cursor拼装表对象。随后自个儿就想写了多少个Utils类似的工具类类来提供一多元增加和删除改查的API,当然这么些API的操作对象都以table对象,随着迭代逐级衍化近年来更加的和睦的light-dao了。

1. 得定义二个一而再BaseDBHelper的DBHelper,大家都懂的:

public class DBHelper extends BaseDBHelper { private static final String DATABASE_NAME = "school.db"; private static final int VERSION = 1; @SuppressLint("StaticFieldLeak") private static DBHelper sSingleton; private DBHelper(Context context) { super(context, DATABASE_NAME, VERSION); } private static DBHelper getSingleton(Context context) { if (sSingleton == null) { synchronized (DBHelper.class) { sSingleton = new DBHelper(context.getApplicationContext; } } return sSingleton; } public static DBUtils with(Context context) { return DBUtils.create(getSingleton; } /** * all table classes should configured here * * @param tableClasses table classes */ @Override protected void onClassLoad(List<Class<? extends Entity>> tableClasses) { tableClasses.add(Student.class); tableClasses.add(Teacher.class); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { super.onUpgrade(db, oldVersion, newVersion); /* upgrade db version by version if (oldVersion < VERSION) { SQL sql = SQLBuilder.buildTableCreateSQL(Student.class); db.execSQL(sql.getSql; } */ }}

2. 然后,定义你的种种表的类,如下为学生表和老师表,且学生表里有先生表ID的外键:

@Table("teacher")public class Teacher extends Entity { @Column(name = "name", notnull = true) public String name;} @Table("student")public class Student extends Entity { @Foreign(Teacher.class) @Column(name = "teacher_id", notnull = true) public long teacherId; @Column(name = "name", notnull = true) public String name; @Column(name = "age", notnull = true) public Integer age;}

3. 末尾就能够经过lightdao实行广泛的数据库增加和删除改查了:

Teacher teacher = new Teacher();teacher.name = "王老师";long teacherId = DBHelper.with.save;// 老师和学生关系是一对多,因此学生表中有老师表的ID作为外键Student student = new Student();student.teacherId = teacherId;student.name = "小学生";student.age = 20;long id = DBHelper.with.save;assertTrue(id > 0);

List<Student> students = new ArrayList<>();for (int i = 0; i < 10; i++) { Student student = new Student(); student.name = "name " + i; student.age = i; student.teacherId = 1; // 假设都是ID为1的教师的学生 students.add;}int count = DBHelper.with.saveAll;assertTrue(count == students.size;

int count = DBHelper.with .withTable(Student.class) .withWhere("age > ?", 5) .applyCount();assertTrue(count > 0);

Student student = DBHelper.with .withTable(Student.class) .applySearchById;assertTrue(student != null);

List<Student> students = DBHelper.with .withTable(Student.class) .applySearchAsList();assertTrue(students.size;

// 类似的还有很多其他以“with”开头的API,如:// withColumns: 只查询指定的column// withGroupBy: 查询分组// withHaving: 分组后的条件筛选// withOrderBy: 排序控制// withLimit: 分页控制// withDistinct: 查询去重List<Student> students = DBHelper.with .withTable(Student.class) .withWhere("age>?", 5) .applySearchAsList();assertTrue(students.size;

ContentValues values = new ContentValues();values.put("name", "hello baby");int count = DBHelper.with .withTable(Student.class) .withWhere("age<?", 5) .applyUpdate;assertTrue(count > 0);

DBUtils dbUtils = DBHelper.with;Student student = dbUtils.withTable(Student.class).applySearchById;assertTrue(student != null);student.name = "testUpdateTable";int count = dbUtils.withTable(Student.class).applyUpdate;assertTrue(count > 0);

int count = DBHelper.with.withTable(Student.class).applyDeleteById;assertTrue(count > 0);

DBUtils dbUtils = DBHelper.with;Student student = dbUtils.withTable(Student.class).applySearchById;assertTrue(student != null);int count = dbUtils.withTable(Student.class).applyDelete;assertTrue(count > 0);

int count = DBHelper.with.withTable(Student.class).withWhere("age>=?", 9).applyDelete();assertTrue(count > 0);

BatchJobs jobs = new BatchJobs();Student student = new Student();student.name = "insert from batch job";student.age = 1;jobs.addInsertJob;// update with table objectstudent = DBHelper.with.withTable(Student.class).applySearchFirst();student.name = "updated from batch job";jobs.addUpdateJob(Student.class, student);// update with idjobs.addUpdateJob(Student.class, student.id, student.toContentValues;// update with conditionjobs.addUpdateJob(Student.class, student.toContentValues(), "age=?", 6);// delete with table objectjobs.addDeleteJob;// delete with idjobs.addDeleteJob(Student.class, 7);// delete with conditionjobs.addDeleteJob(Student.class, "age<?", 3);boolean success = DBHelper.with.applyBatchJobs;assertTrue;

// 因为跨表查询的结果来自于多个表,所以得重新定义返回结果的对象,并通过aliasName指定此字段来自于哪个表中的哪个字段public class Relation extends Query { @Column(name = "teacher_id", aliasName = "student._id as teacher_id") public long teacherId; @Column(name = "teacher_name", aliasName = "teacher.name as teacher_name") public String teacherName; @Column(name = "student_id", aliasName = "student._id as student_id") public long studentId; @Column(name = "student_name", aliasName = "student.name as student_name") public String studentName; @Column(name = "age") public int studentAge;}List<Relation> list = DBHelper.with .withQuery(Relation.class) .applySearchAsList();System.out.println(list.size;

数据库晋级其实什么也不用做,因为是全自动的,因为重写了onUpgrade():

@Overridepublic final void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { autoMigrate(db, mTableClasses);}private void autoMigrate(SQLiteDatabase db, List<Class<? extends Entity>> tableClasses) { for (Class<? extends Entity> clazz : tableClasses) { String tableName = ReflectTools.getTableName; boolean exist = ReflectTools.isTableExist(db, tableName); if  { Field[] fields = ReflectTools.getClassFields; for (Field field : fields) { Column column = field.getAnnotation(Column.class); if (column == null) { continue; } String columnName = !TextUtils.isEmpty(column.name ? column.name() : field.getName(); String dataType = ReflectTools.getDataTypeByField; boolean columnExist = ReflectTools.isColumnExist(db, tableName, columnName); if (!columnExist) { db.execSQL("ALTER TABLE " + tableName + " ADD " + columnName + " " + dataType); } } } else { db.execSQL(SQLBuilder.buildCreateSQL.getSql; } }}static boolean isTableExist(SQLiteDatabase db, String tableName) { Cursor cursor = null; try { cursor = db.rawQuery("SELECT count FROM sqlite_master WHERE type='table' AND name=?", new String[]{tableName}); boolean hasNext = cursor.moveToNext(); return hasNext && cursor.getInt > 0; } finally { if (cursor != null) { cursor.close(); } }}static boolean isColumnExist(SQLiteDatabase db, String tableName, String columnName) { Cursor cursor = null; try { cursor = db.rawQuery("SELECT count FROM sqlite_master WHERE tbl_name = ? AND (sql LIKE ? OR sql LIKE ?);", new String[]{tableName, "%(" + columnName + "%", "%, " + columnName + " %"}); boolean hasNext = cursor.moveToNext(); return hasNext && cursor.getInt > 0; } finally { if (cursor != null) { cursor.close(); } }}

连锁落实可查阅light-dao:

本文由365bet亚洲版登录发布于计算机网络,转载请注明出处:写一个简单的Android版本的ORM

您可能还会对下面的文章感兴趣: