標籤:android 架構 xutils
架構地址:https://github.com/wyouflf/xUtils
需要的許可權
<uses-permissionandroid:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
建立資料庫
DaoConfig config = new DaoConfig(context);
config.setDbName("xUtils-demo"); //db名
config.setDbVersion(1); //db版本
DbUtils db = DbUtils.create(config);//db還有其他的一些構造方法,比如含有更新表版本的監聽器的
建立表
db.createTableIfNotExist(User.class); //建立一個表User
db.save(user);//在表中儲存一個user對象。最初執行儲存動作時,也會建立User表
刪除表
db.dropTable(User.class);
開啟事務
db.configAllowTransaction(true);
db相關Annotation
@Check check約束
@Column 列名
@Finder 一對多、多對一、多對多關係(見sample的Parent、Child中的使用)
@Foreign 外鍵
@Id 主鍵,當為int類型時,預設自增。 非自增時,需要設定id的值
@NoAutoIncrement 不自增
@NotNull 不為空白
@Table 表名
@Transient 不寫入資料庫表結構
@Unique 唯一約束
一些常用方法
DbUtils db = DbUtils.create(this);User user = new User(); //這裡需要注意的是User對象必須有id屬性,或者有通過@ID註解的屬性user.setEmail("[email protected]");user.setName("wyouflf");db.save(user); // 使用saveBindingId儲存實體時會為實體的id賦值...// 尋找Parent entity = db.findById(Parent.class, parent.getId());List<Parent> list = db.findAll(Parent.class);//通過類型尋找Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","=","test"));// IS NULLParent Parent = db.findFirst(Selector.from(Parent.class).where("name","=", null));// IS NOT NULLParent Parent = db.findFirst(Selector.from(Parent.class).where("name","!=", null));// WHERE id<54 AND (age>20 OR age<30) ORDER BY id LIMIT pageSize OFFSET pageOffsetList<Parent> list = db.findAll(Selector.from(Parent.class) .where("id" ,"<", 54) .and(WhereBuilder.b("age", ">", 20).or("age", " < ", 30)) .orderBy("id") .limit(pageSize) .offset(pageSize * pageIndex));// op為"in"時,最後一個參數必須是數組或Iterable的實作類別(例如List等)Parent test = db.findFirst(Selector.from(Parent.class).where("id", "in", new int[]{1, 2, 3}));// op為"between"時,最後一個參數必須是數組或Iterable的實作類別(例如List等)Parent test = db.findFirst(Selector.from(Parent.class).where("id", "between", new String[]{"1", "5"}));DbModel dbModel = db.findDbModelAll(Selector.from(Parent.class).select("name"));//select("name")只取出name列List<DbModel> dbModels = db.findDbModelAll(Selector.from(Parent.class).groupBy("name").select("name", "count(name)"));...List<DbModel> dbModels = db.findDbModelAll(sql); // 自訂sql查詢db.execNonQuery(sql) // 執行自訂sql...
Android xUtils架構(一)DbUtils