想找个android上的数据库框架,一开始接触了XUtils,没什么文档,代码看着也别扭,不知从何下手,直接放弃,google搜索后,对比了下,选择了greenDao(为何?看着那牛逼的对比报表,以及官网简单易懂的使用介绍)。
greenDao会为我们生成一些必要的类,这要求创建一个独立的java工程,定义好表格格式,运行java工程,生成相应的类
数据库操作不外乎,创建表格,插入,删除,更新记录,查询。这里会在greenDao原有的Sample基础上,增加一个新表 Device ,并对表Device进行一系列操作。
定义表格
public static void main(String[] args) throws Exception {
Schema schema = new Schema(1000, "de.greenrobot.daoexample");
addNote(schema);
// 添加TAble Device定义
addDevice(schema);
addCustomerOrder(schema);
new DaoGenerator (). generateAll ( schema , "E:\\ws\\git\\greenDAO\\DaoExample\\src\\main\\java" );}
private static void addNote(Schema schema) {
Entity note = schema.addEntity("Note");
note.addIdProperty();
note.addStringProperty("text").notNull();
note.addStringProperty("comment");
note.addDateProperty("date");
}
// Table Device的规则
private static void addDevice ( Schema schema ){
Entity device = schema.addEntity("Device");
device.addIdProperty();
device.addStringProperty("type");
device.addStringProperty("rawName");
device.addStringProperty("nickName");
device.addStringProperty("macString");
}
编译运行Java工程DaoExampleGenerator后,会生成Device相关的类
添加Device表的操作对象
private DeviceDao deviceDao;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();
// 添加操作对象
deviceDao = daoSession.getDeviceDao();
...
}
添加行
private void addDevice(){
Device device = new Device();
mDevice = device;
device.setId(null);
device.setMacString("akdjgalghalkd");
device.setNickName("class five");
device.setRawName("raw name five");
device.setType("tv");
deviceDao.insert(device);
}
更新行
private void updateDeviceDb(){
if (mDevice != null){
mDevice.setNickName("nick name 2");
deviceDao.insertOrReplace(mDevice);
}
}
查询
private void queryDevice(){
Query query = deviceDao.queryBuilder().where(DeviceDao.Properties.Type.eq("tv")).build();
List<Device> deviceList = query.list();
if (deviceList != null && deviceList.size() > 0){
Toast.makeText(this, "query result count=" + deviceList.size(), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "query result count = 0" , Toast.LENGTH_SHORT).show();
}
}
删除行
private void deleteDevice(){
if (mDevice != null){
deviceDao.delete(mDevice);
}
}
验证工具
adb命令行下可以使用 sqlite3 进行操作,不是很直观,我个人是将db文件pull到windows,然后用 Sqliteman查看
题外话:
添加表格时碰到了点问题
问题一:如何在Android Studio中编译Java工程
1.添加一个 "Application"
2. 配置Main class
3. 配置classpath
问题二:编译DaoExampleGenerator时,编译不过去,如何修改
编译出错
This program comes with ABSOLUTELY NO WARRANTY
Exception in thread "main" freemarker.template.TemplateNotFoundException: Template not found for name "dao.ftl".
The name was interpreted by this TemplateLoader: ClassTemplateLoader(resourceLoaderClass=de.greenrobot.daogenerator.DaoGenerator, basePackagePath="/").
at freemarker.template.Configuration.getTemplate(Configuration.java:1833)
at freemarker.template.Configuration.getTemplate(Configuration.java:1646)
at de.greenrobot.daogenerator.DaoGenerator.<init>(DaoGenerator.java:65)
at de.greenrobot.daogenerator.gentest.ExampleDaoGenerator.main(ExampleDaoGenerator.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
需要修改DaoGenerator 的构造函数
public DaoGenerator() throws IOException {
System.out.println("greenDAO Generator");
System.out.println("Copyright 2011-2015 Markus Junginger, greenrobot.de. Licensed under GPL V3.");
System.out.println("This program comes with ABSOLUTELY NO WARRANTY");
patternKeepIncludes = compilePattern("INCLUDES");
patternKeepFields = compilePattern("FIELDS");
patternKeepMethods = compilePattern("METHODS");
Configuration config = new Configuration(Configuration.VERSION_2_3_23);
// 改为绝对路劲
// config.setClassForTemplateLoading(this.getClass(), "/");
config.setDirectoryForTemplateLoading(new File("E:\\ws\\git\\greenDAO\\DaoGenerator\\src-template"));
templateDao = config.getTemplate("dao.ftl");
templateDaoMaster = config.getTemplate("dao-master.ftl");
templateDaoSession = config.getTemplate("dao-session.ftl");
templateEntity = config.getTemplate("entity.ftl");
templateDaoUnitTest = config.getTemplate("dao-unit-test.ftl");
templateContentProvider = config.getTemplate("content-provider.ftl");
}
DaoExampleGenerator生成类文件出错,找不到路径,修改
public class ExampleDaoGenerator {
public static void main(String[] args) throws Exception {
Schema schema = new Schema(1000, "de.greenrobot.daoexample");
addNote(schema);
addDevice(schema);
addCustomerOrder(schema);
// 改成绝对路径
// new DaoGenerator().generateAll(schema, "../DaoExample/src/main/java");
new DaoGenerator().generateAll(schema, "E:\\ws\\git\\greenDAO\\DaoExample\\src\\main\\java");
}
...
}
问题三:插入表格失败。
增加了Device表格的定义后,往Device表格插入数据,出现崩溃
这是因为原有规则的db文件已经存在(note-db),没有创建具有Device表的db文件,所以插入崩溃。只要删除db文件就行了。