sqlGenerator
APP比较简单或者APP@R_301_457@操作比较少,简单的几张表,少量的数据存储。 这个时候其实没有必要去使用第三方的ORM库
sqlGenerator
致力于在不使用ORM库的情况下,通过生成一些boilerplate code
方式简化@R_301_457@操作,从而减轻工作量
现在sqlGenerator
已经支持根据Model的定义自动生成相应的Table定义,避免编写枯燥的代码
Model定义如下
@Table(name = "User")
@Index(name = "name_age_index",columns = {"name","age"},unique = true)
public class User {
@PrimaryKey
public long id;
@Column(unique = true,notNULL = true)
public String name;
@Serializer(
serializedTypeCanonicalName = String.class,serializerCanonicalName = FileSerializer.class)
public File avtar;
@Column(check = "age>16")
public int age;
@Column(name = "address_id")
public Address address;
@ForeignKey(referenceTableName = "Group",referenceColumnName = "id",action = "ON UPDATE CASCADE")
public long groupId;
}
最终会生成表的外观
类
public final class UserContract {
public static final String TABLE_NAME = "User";
public static final String ID_COLUMN = "id";
public static final String NAME_COLUMN = "name";
public static final String AVTAR_COLUMN = "avtar";
public static final String AGE_COLUMN = "age";
public static final String ADDRESS_ID_COLUMN = "address_id";
public static final String GROUPID_COLUMN = "groupId";
public static final String CREATE_TABLE_sql = "CREATE TABLE IF NOT EXISTS User(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL UNIQUE,avtar TEXT,age INTEGER CHECK(age>16),address_id TEXT,groupId INTEGER,FOREIGN KEY(groupId) REFERENCES Group(id) ON UPDATE CASCADE)";
public static final String CREATE_NAME_AGE_INDEX_sql = "CREATE INDEX name_age_index ON User(name,age)";
public UserContract() {
}
public static void createTable(sqliteDatabase db) {
db.execsql("CREATE TABLE IF NOT EXISTS User(id INTEGER PRIMARY KEY AUTOINCREMENT,FOREIGN KEY(groupId) REFERENCES Group(id) ON UPDATE CASCADE)");
}
public static void createIndex(sqliteDatabase db) {
db.execsql("CREATE INDEX name_age_index ON User(name,age)");
}
public static void dropTable(sqliteDatabase db) {
db.execsql("DROP TABLE IF EXISTS User");
}
}
Download
buildscript { repositories { mavenCentral() }
dependencies { classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' }
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies { compile 'com.github.tubb.sqlgenerator:sqlgenerator-annotations:0.0.3-SNAPSHOT' apt 'com.github.tubb.sqlgenerator:sqlgenerator-compiler:0.0.3-SNAPSHOT' }
Usage
定义好Model类之后重新构建应用,会生成以ModelNameContract命名的表外观
类,可以在moduleName/build/intermediates/classes
目录下查看
./gradlew clean build
Note
sqlGenerator
还处于开发阶段,功能不是很稳定,正式项目请谨慎使用。非常希望有兴趣的朋友来一起完善这个library,这里写链接内容