ORMLite支持从配置文件里加载数据,在Dao数据库映射类被创建时,就不需要去访问实体类的注解了,节省了时间
1.继承OrmLiteConfigUtil
public class DatabaseConfigUtil extends OrmLiteConfigUtil {
private static final Class<?>[] classes = new Class[] {
SimpleData.class,
};
public static void main(String[] args) throws Exception {
writeConfigFile("ormlite_config.txt", classes);
}
}
2.在Android项目下以Java Application方式运行OrmLiteConfigUtil类,控制台输出提示:(前提raw文件夹必须存在)
Writing configurations to /HelloAndroid/./res/raw/ormlite_config.txt Wrote config for class com.example.helloandroid.SimpleData Done.
注:在Android Studio中运行时会出现“Could not find raw directory which is typically in the res directory”,
将文件名替换为完整路径:
writeConfigFile(new File("com/youApplcation/../res/raw/ormlite_config.txt"), classes);
编辑配置
运行前删除 Make,应为如果ormlite_config.txt不存在,运行是会出错
如果运行Main()函数报错
Exception in thread "main" java.lang.ClassNotFoundException: my.package.DatabaseConfigUtil
删除运行配置,重新运行
参考:http://stackoverflow.com/questions/17298773/android-studio-run-configuration-for-ormlite-config-generation
![]()
成功!刷新项目后
在res/raw文件夹下出现名为“
ormlite_config.txt”的配置文件
配置文件内容大致如下:
#
# generated on 2011/09/15 01:42:02
#
# --table-start--
dataClass=com.example.helloandroid.SimpleData
tableName=simpledata
# --table-fields-start--
# --field-start--
fieldName=id
canBeNull=true
generatedId=true
…
R文件会生成对应id,就可以作为资源直接引用了
public final class R { … public static final class raw { public static final int ormlite_config=0x7f040000; } … }
注:当映射实体类结构改变时必须重新生成配置文件
3.DatabaseHelper
构造函数修改如下
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION,
R.raw.ormlite_config);
}