1、环境准备
1.1 jar包
1.2 生成器的代码
2、需要编写生重点内容成操作数据的代码
/**
* Generates entities and DAOs for the example project DaoExample.
*
* Run it as a Java application (not Android).
*
* @author Markus
*/
public class ExampleDaoGenerator {
public static void main(String[] args) throws Exception {
//第一个为数据库的版本号,第二个是自动生成数据库相关文件的包名
Schema schema = new Schema(1000, "com.smartspyeye.livevideo.dao");
// 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。
addNote(schema);
// 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录这里我创建一个java-gen的文件夹。
new DaoGenerator().generateAll(schema, "../greendaoGenerator/src-gen");
}
private static void addNote(Schema schema) {
//"HistoryMessage"与数据库对应的javabean对象
Entity note = schema.addEntity("HistoryMessage");
//设置主键字段
note.addIdProperty();
//设置Javabean属性与数据库SendUserName字段
note.addStringProperty("SendUserName");
//设置Javabean属性与数据库MsgCount字段
note.addStringProperty("MsgCount");
}
3、执行步骤2,自动生成如下代码
4、编写数据库操作类的方法 增 删 改 查
public class AvPresenter {
public static final String dbName = "audioVideo.db";
// public static final String dbName = "HistoryMessage.db";
private DaoMaster.DevOpenHelper helper;
private DaoMaster daoMaster;
private DaoSession daoSession;
private HistoryMessageDao historyMessageDao;
public AvPresenter(Context context) {
helper = new DaoMaster.DevOpenHelper(context, dbName, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
daoSession = daoMaster.newSession();
}
public AvPresenter(Context context, String dbName) {
helper = new DaoMaster.DevOpenHelper(context, dbName, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
daoSession = daoMaster.newSession();
}
// 添加一条数据
public long add(HistoryMessage hs) throws Exception {
return daoSession.insertOrReplace(hs);
}
// 更新单条数据
public void update(HistoryMessage hs) throws Exception {
daoSession.update(hs);
}
// 查询所有数据
public List<HistoryMessage> loadHistoryMessageAll() throws Exception {
return daoSession.getHistoryMessageDao().loadAll();
}
// 删除单条数据
public void deleteHistoryMessage(HistoryMessage hs) throws Exception {
daoSession.delete(hs);
}
// 删除所有数据
public void deleteHistoryMessageAll() throws Exception {
daoSession.deleteAll(HistoryMessage.class);
}
/**
* 根据用户名条件查询用户信息,映射到Javabean对象
*
* @param SendUserName
* @return
* @throws Exception
*/
public HistoryMessage getMessageBySendUserName(String SendUserName)throws Exception {
Query<HistoryMessage> build = daoSession.queryBuilder(HistoryMessage.class).where(Properties.SendUserName.eq(SendUserName)).build();
List<HistoryMessage> list = build.list();
return list.get(0);
}
public void close() {
if (daoSession != null) {
daoSession.clear();
daoSession = null;
}
if (helper != null) {
helper.close();
helper = null;
}
}
}