DaoManager
/**
* 1、创建数据库
* 2、创建数据库的表
* 3、包含对数据库的CRUD
* 4、对数据库的升级
*/
public class DaoManager {
private static final String TAG = DaoManager.class.getSimpleName();
private static final String DB_NAME="mydb.sqlite";//数据库名称
private volatile static DaoManager manager;//多线程访问
private static DaoMaster.DevOpenHelper helper;
private static DaoMaster daoMaster;
private static DaoSession daoSession;
private Context context;
/**
* 使用单例模式获得操作数据库的对象
* @return
*/
public static DaoManager getInstance(){
DaoManager instance = null;
if (manager==null){
synchronized (DaoManager.class){
if (instance==null){
instance = new DaoManager();
manager = instance;
}
}
}
return instance;
}
public void init(Context context){
this.context = context;
}
/**
* 判断是否存在数据库,如果没有则创建数据库
* @return
*/
public DaoMaster getDaoMaster(){
if (daoMaster==null){
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context,DB_NAME,null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
/**
* 完成对数据库的添加、删除、修改、查询的操作,仅仅是一个接口
* @return
*/
public DaoSession getDaoSession(){
if (daoSession==null){
if (daoMaster==null){
daoMaster = getDaoMaster();
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
/**
* 打开输出日志的操作,默认是关闭的
*/
public void setDebug(){
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
/**
* 关闭所有的操作,数据库开启的时候,使用完毕了必须要关闭
*/
public void closeConnection(){
closeHelper();
closeDaoSession();
}
public void closeHelper(){
if (helper!=null){
helper.close();;
helper = null;
}
}
public void closeDaoSession(){
if (daoSession!=null){
daoSession.clear();;
daoSession = null;
}
}
}
CommonUtils
/**
* 完成对某一张表的具体操作,ORM 操作的是对象,Student
*/
public class CommonUtils {
private DaoManager manager;
public CommonUtils(Context context) {
manager = DaoManager.getInstance();
manager.init(context);
}
/**
* 完成对数据库中student 表的插入操作
*
* @param student
* @return
*/
public boolean insertStudent(Student student) {
boolean flag = false;
flag = manager.getDaoSession().insert(student) != -1 ? true : false;
Log.i("CommonUtils", "----insertStudent--result is -->>" + flag);
return flag;
}
/**
* 插入多条记录,需要开辟新的线程
*
* @param students
* @return
*/
public boolean insertMultStudent(final List<Student> students) {
boolean flag = false;
try {
manager.getDaoSession().runInTx(new Runnable() {
@Override
public void run() {
for (Student student : students) {
manager.getDaoSession().insertOrReplace(student);
}
}
});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 完成对student的某一条记录的修改
*
* @param student
* @return
*/
public boolean updateStudent(Student student) {
boolean flag = false;
try {
manager.getDaoSession().update(student);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* @param student
* @return
*/
public boolean deleteStudent(Student student) {
boolean flag = false;
try {
//按照指定的id进行删除 delete from student where _id = ?
manager.getDaoSession().delete(student);
//manager.getDaoSession().deleteAll();//删除所有的记录
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
*
*/
public void deleteAllStudent(Class cls){
manager.getDaoSession().deleteAll(cls);
}
/**
* 返回多行记录
*
* @return
*/
public List<Student> listAll() {
return manager.getDaoSession().loadAll(Student.class);
}
/**
* 按照主键返回单行记录
*
* @param key
* @return
*/
public Student listOneStudent(long key) {
return manager.getDaoSession().load(Student.class, key);
}
public void query1() {
//使用native sql进行查询操作,
List<Student> list = manager.getDaoSession().queryRaw(Student.class, " where name like ? and _id > ? ", new String[]{"%李%", "1002"});
Log.i("--->>", "" + list);
}
/**
* select * from student where name like ? or name =? or
* < <= >= != in between and
* select * from student where age > 23 and address like "江西"
*/
public void query2() {
//查询构建器
QueryBuilder<Student> builder = manager.getDaoSession().queryBuilder(Student.class);
List<Student> list = builder.where(StudentDao.Properties.Age.ge(23)).where(StudentDao.Properties.Address.like("江西")).list();
Log.i("--->>", "" + list);
}
public void query3() {
//逻辑与 和 逻辑或 是双目运算符
QueryBuilder<Student> builder = manager.getDaoSession().queryBuilder(Student.class);
//select * from student where (address='北京' or age > 50) and name like '%张%'
builder.whereOr(StudentDao.Properties.Address.eq("北京"), StudentDao.Properties.Age.ge(50));
builder.whereOr(StudentDao.Properties.Id.ge(2), StudentDao.Properties.Age.ge(10)).limit(3);//区前三条数据
//builder.where(StudentDao.Properties.Name.like("张"));
List<Student> list = builder.list();
Log.i("--->>", "" + list);
}
}
MainActivity
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private CommonUtils commonUtils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commonUtils = new CommonUtils(this);
}
//插入数据库的操作
public void insertData(View view) {
Log.i(TAG, "insert Data");
Student student = new Student();
student.setAddress("江西");
student.setName("李四");
student.setAge(24);
// student.setId(1001l);
commonUtils.insertStudent(student);
}
public void insertMultData(View view) {
Log.i(TAG, "insert mult Data");
List<Student> list = new ArrayList<>();
Student student1 = new Student();
student1.setAge(23);
student1.setName("张三");
student1.setAddress("北京育知同创科技有限公司");
Student student2 = new Student();
student2.setAge(45);
student2.setName("李四");
student2.setAddress("北京");
Student student3 = new Student();
student3.setAge(56);
student3.setName("张学友");
student3.setAddress("杭州");
Student student4 = new Student();
student4.setAge(12);
student4.setName("刘德华");
student4.setAddress("香港");
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
commonUtils.insertMultStudent(list);//插入多条数据
}
public void updateData(View view) {
//update student set name='jack' where id = 1001;
Student student = new Student();
student.setId(1001l);
student.setAge(100);
student.setName("jack");
student.setAddress("北京育知同创科技有限公司");
commonUtils.updateStudent(student);
}
public void deleteData(View view) {
// Student student = new Student();
// student.setId(1001l);
//delete from student where _id = 1001;
commonUtils.deleteAllStudent(Student.class);
}
public void queryOneORMore(View view) {
// List<Student> list = commonUtils.listAll();
// Log.i(TAG,list.toString());
// Log.i(TAG, commonUtils.listOneStudent(1001l) + "");
commonUtils.query3();
}
/**
* 使用复合条件进行查询
*
* @param view
*/
public void queryBuilder(View view) {
commonUtils.deleteAllStudent(Student.class);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="cn.data.laoluo.greendao_projects.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加数据"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:onClick="insertData"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加多条记录"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignParentStart="true"
android:layout_alignEnd="@+id/button"
android:onClick="insertMultData"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改一条数据"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignParentStart="true"
android:layout_alignEnd="@+id/button2"
android:onClick="updateData"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除单条记录"
android:id="@+id/button4"
android:layout_below="@+id/button3"
android:layout_alignParentStart="true"
android:layout_alignEnd="@+id/button3"
android:onClick="deleteData"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查询单行/多行记录"
android:id="@+id/button5"
android:layout_below="@+id/button4"
android:layout_alignParentStart="true"
android:layout_alignEnd="@+id/button4"
android:onClick="queryOneORMore"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="使用QueryBuilder查询"
android:id="@+id/button6"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_alignEnd="@+id/button5"
android:onClick="queryBuilder"
/>
</RelativeLayout>
使用的Java代码:
public class DaoMaker {
public static void main(String[] args){
//生成数据库的实体类XXentity 对应的是数据库的表
Schema schema = new Schema(1,"com.student.entity");
addStudent(schema);
schema.setDefaultJavaPackageDao("com.student.dao");
try{
new DaoGenerator().generateAll(schema,"/Users/luoliwen/AndroidStudioProjects/GreenDao_Projects/app/src/main/java-gen");
}catch(Exception e){
e.printStackTrace();
}
}
//创建数据库的表
private static void addStudent(Schema schema){
Entity entity =schema.addEntity("Student");//创建数据库的表
entity.addIdProperty();//主键 是 int类型
entity.addStringProperty("name");//对应的数据库的列
entity.addStringProperty("address");//对应的数据库的列
entity.addIntProperty("age");//对应的数据库的列
}
}
利用GreenDao自动生成的代码如下:
dao包下
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
StudentDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(SQLiteDatabase db, boolean ifExists) {
StudentDao.dropTable(db, ifExists);
}
public static abstract class OpenHelper extends SQLiteOpenHelper {
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
public DaoMaster(SQLiteDatabase db) {
super(db, SCHEMA_VERSION);
registerDaoClass(StudentDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
}
public class DaoSession extends AbstractDaoSession {
private final DaoConfig studentDaoConfig;
private final StudentDao studentDao;
public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
studentDaoConfig = daoConfigMap.get(StudentDao.class).clone();
studentDaoConfig.initIdentityScope(type);
studentDao = new StudentDao(studentDaoConfig, this);
registerDao(Student.class, studentDao);
}
public void clear() {
studentDaoConfig.getIdentityScope().clear();
}
public StudentDao getStudentDao() {
return studentDao;
}
}
public class DaoSession extends AbstractDaoSession {
private final DaoConfig studentDaoConfig;
private final StudentDao studentDao;
public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
studentDaoConfig = daoConfigMap.get(StudentDao.class).clone();
studentDaoConfig.initIdentityScope(type);
studentDao = new StudentDao(studentDaoConfig, this);
registerDao(Student.class, studentDao);
}
public void clear() {
studentDaoConfig.getIdentityScope().clear();
}
public StudentDao getStudentDao() {
return studentDao;
}
}
public class StudentDao extends AbstractDao<Student, Long> {
public static final String TABLENAME = "STUDENT";
/**
* Properties of entity Student.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Name = new Property(1, String.class, "name", false, "NAME");
public final static Property Address = new Property(2, String.class, "address", false, "ADDRESS");
public final static Property Age = new Property(3, Integer.class, "age", false, "AGE");
};
public StudentDao(DaoConfig config) {
super(config);
}
public StudentDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"STUDENT\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"NAME\" TEXT," + // 1: name
"\"ADDRESS\" TEXT," + // 2: address
"\"AGE\" INTEGER);"); // 3: age
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"STUDENT\"";
db.execSQL(sql);
}
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, Student entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
String address = entity.getAddress();
if (address != null) {
stmt.bindString(3, address);
}
Integer age = entity.getAge();
if (age != null) {
stmt.bindLong(4, age);
}
}
/** @inheritdoc */
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
/** @inheritdoc */
@Override
public Student readEntity(Cursor cursor, int offset) {
Student entity = new Student( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // address
cursor.isNull(offset + 3) ? null : cursor.getInt(offset + 3) // age
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, Student entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setAddress(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setAge(cursor.isNull(offset + 3) ? null : cursor.getInt(offset + 3));
}
/** @inheritdoc */
@Override
protected Long updateKeyAfterInsert(Student entity, long rowId) {
entity.setId(rowId);
return rowId;
}
/** @inheritdoc */
@Override
public Long getKey(Student entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
entity包下
public class Student {
private Long id;
private String name;
private String address;
private Integer age;
public Student() {
}
public Student(Long id) {
this.id = id;
}
public Student(Long id, String name, String address, Integer age) {
this.id = id;
this.name = name;
this.address = address;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}