Greendao的使用

来源:互联网 发布:郎咸平小三 知乎 编辑:程序博客网 时间:2024/05/17 05:57

Greendao(操作数据库的框架):是一种非常简单的框架。
一共分为四层:
1.DaoMaster—>最大的一层
2.DaoSession—>会话层
3.xxxDao—>真正的操作层(管理列表的)
想要使用Greendao必须添加lib
这里写图片描述
然后选择
这里写图片描述
添加依赖
这里写图片描述
然后我们创建一个GreendaoClass

public class GreendaoClass {    public static void main(String[] args) {        //首先创建数据图表(数据库框架)        //两个参数,第一个参数:数据库的版本号,第二个参数:使我们自动生成代码的包名        Schema schema = new Schema(1, "com.an.greendao");        //调用添加方法        addNote(schema);        //自动生成代码,两个参数,第一个参数:图表对象,第二个参数:是自动生成的代码路径        try {            new DaoGenerator().generateAll(schema,"./app/src/main/java");        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 这个方法是为我们数据库添加所需的内容     *     * @param schema     */    public static void addNote(Schema schema) {        //添加表名        Entity entity = schema.addEntity("Person");        //加入id,并且自增        entity.addIdProperty().autoincrement().primaryKey();        //添加类的属性,根据属性生成相应的表中字段        entity.addStringProperty("name");        entity.addIntProperty("age");        entity.addStringProperty("sex");    }}

这样就配置完前一部分了,运行写的GreendaoClass,然后等一会儿,就会帮你创建四个类了。
这里写图片描述
创建的四个类分别是DaoMaster、DaoSession、Person、Person。
DaoMaster.java

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) {        PersonDao.createTable(db, ifNotExists);    }    /** Drops underlying database table using DAOs. */    public static void dropAllTables(SQLiteDatabase db, boolean ifExists) {        PersonDao.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(PersonDao.class);    }    public DaoSession newSession() {        return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);    }    public DaoSession newSession(IdentityScopeType type) {        return new DaoSession(db, type, daoConfigMap);    }}

DaoSession.java

public class DaoSession extends AbstractDaoSession {    private final DaoConfig personDaoConfig;    private final PersonDao personDao;    public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>            daoConfigMap) {        super(db);        personDaoConfig = daoConfigMap.get(PersonDao.class).clone();        personDaoConfig.initIdentityScope(type);        personDao = new PersonDao(personDaoConfig, this);        registerDao(Person.class, personDao);    }    public void clear() {        personDaoConfig.getIdentityScope().clear();    }    public PersonDao getPersonDao() {        return personDao;    }}

Person.java

public class Person {    private Long id;    private String name;    private Integer age;    private String sex;    public Person() {    }    public Person(Long id) {        this.id = id;    }    public Person(Long id, String name, Integer age, String sex) {        this.id = id;        this.name = name;        this.age = age;        this.sex = sex;    }    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 Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }}

PersonDao.java

public class PersonDao extends AbstractDao<Person, Long> {    public static final String TABLENAME = "PERSON";    /**     * Properties of entity Person.<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 Age = new Property(2, Integer.class, "age", false, "AGE");        public final static Property Sex = new Property(3, String.class, "sex", false, "SEX");    };    public PersonDao(DaoConfig config) {        super(config);    }    public PersonDao(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 + "\"PERSON\" (" + //                "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id                "\"NAME\" TEXT," + // 1: name                "\"AGE\" INTEGER," + // 2: age                "\"SEX\" TEXT);"); // 3: sex    }    /** Drops the underlying database table. */    public static void dropTable(SQLiteDatabase db, boolean ifExists) {        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"PERSON\"";        db.execSQL(sql);    }    /** @inheritdoc */    @Override    protected void bindValues(SQLiteStatement stmt, Person 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);        }        Integer age = entity.getAge();        if (age != null) {            stmt.bindLong(3, age);        }        String sex = entity.getSex();        if (sex != null) {            stmt.bindString(4, sex);        }    }    /** @inheritdoc */    @Override    public Long readKey(Cursor cursor, int offset) {        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);    }        /** @inheritdoc */    @Override    public Person readEntity(Cursor cursor, int offset) {        Person entity = new Person( //            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.getInt(offset + 2), // age            cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3) // sex        );        return entity;    }    /** @inheritdoc */    @Override    public void readEntity(Cursor cursor, Person 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.setAge(cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2));        entity.setSex(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));     }    /** @inheritdoc */    @Override    protected Long updateKeyAfterInsert(Person entity, long rowId) {        entity.setId(rowId);        return rowId;    }    /** @inheritdoc */    @Override    public Long getKey(Person entity) {        if(entity != null) {            return entity.getId();        } else {            return null;        }    }    /** @inheritdoc */    @Override        protected boolean isEntityUpdateable() {        return true;    }}

还需需要添加一个依赖,在build.gradle(Module:app)中添加
这里写图片描述

现在所有的东西都弄好了之后,我们就可以使用了

public class MainActivity extends AppCompatActivity {    private SQLiteDatabase db;//数据库    private DaoMaster daoMaster;//管理者    private DaoSession daoSession;//回话者    private PersonDao personDao;//数据库内相应表的操作对象    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initData();    }    public void initData() {        //我们进行各种初始化,第一个参数:context,第二个参数:数据库的名字,打三个参数游标工厂,设置为null        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "greendao.db", null);        //初始化数据库        db = helper.getWritableDatabase();        //初始化DaoMaster        daoMaster = new DaoMaster(db);        //初始化daoSession        daoSession = daoMaster.newSession();        //初始化personDao        personDao = daoSession.getPersonDao();        //删除所有,这里为了防止id冲突,事先将数据库里的所有内容清空        personDao.deleteAll();        List<Person> list = new ArrayList<>();        for (int i = 0; i < 50; i++) {            Person person = new Person((long) i, "baby", 21, "男");            //增添方法            personDao.insert(person);        }        //根据id删除内容        personDao.deleteByKey(5l);        //修改数据库内容        personDao.update(new Person(2l, "宝宝", 15, "女"));        //查看数据库        List<Person> personList = personDao.queryBuilder().list();        for (Person person : personList) {            Log.d("TAG", "person:" + person.getName() +                    person.getId() + person.getSex()                    + person.getAge());        }    }}

看了上面的代码是不是感觉使用Greendao来操作数据库方便了很多,当然我们的实际情况并不是只有一张表,所以我们需要把Greendao封装成单例,这样就能保证我们的我所用的Greendao的对象是一个了!接下来我们封装下一下吧!

public class GreendaoSingle {    private SQLiteDatabase db;//数据库    private DaoMaster daoMaster;//管理者    private DaoSession daoSession;//回话者    private PersonDao personDao;//数据库内相应表的操作对象    private Context context;    private DaoMaster.DevOpenHelper helper;    public DaoMaster.DevOpenHelper getHelper() {        if (helper == null) {            helper = new DaoMaster.DevOpenHelper(context, "Person.db", null);        }        return helper;    }    private static GreendaoSingle ourInstance = new GreendaoSingle();    public static GreendaoSingle getInstance() {        return ourInstance;    }    private GreendaoSingle() {        //这里需要一个context,所以我们又新建了一个自己的MyApp        context = MyApp.getContext();    }    public SQLiteDatabase getDb() {        if (db == null) {            db = getHelper().getWritableDatabase();        }        return db;    }    public DaoMaster getDaoMaster() {        if (daoMaster == null) {            daoMaster = new DaoMaster(getDb());        }        return daoMaster;    }    public DaoSession getDaoSession() {        if (daoSession == null) {            daoSession = getDaoMaster().newSession();        }        return daoSession;    }    public PersonDao getPersonDao() {        if (personDao == null) {            personDao = getDaoSession().getPersonDao();        }        return personDao;    }}

MyApp.java

public class MyApp extends Application {    private static Context context;    @Override    public void onCreate() {        super.onCreate();        context = this;    }    public static Context getContext() {        return context;    }}

当然我们新建好的MyApp,还需要在清单文件中给Application添加一个name属性就可以了,
然后我们就可以使用单例的形式来操作了,

public class MainActivity extends AppCompatActivity {    private SQLiteDatabase db;//数据库    private DaoMaster daoMaster;//管理者    private DaoSession daoSession;//回话者    private PersonDao personDao;//数据库内相应表的操作对象    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initData();    }    public void initData() {        //使用单列来创建PersonDao,在所有类当中,我们保证只是用一个PersonDao        personDao = GreendaoSingle.getInstance().getPersonDao();        //删除所有,这里为了防止id冲突,事先将数据库里的所有内容清空        personDao.deleteAll();        List<Person> list = new ArrayList<>();        for (int i = 0; i < 50; i++) {            Person person = new Person((long) i, "baby", 21, "男");            //增添方法            personDao.insert(person);        }        //根据id删除内容        personDao.deleteByKey(5l);        //修改数据库内容        personDao.update(new Person(2l, "宝宝", 85, "女"));        //查看数据库        List<Person> personList = personDao.queryBuilder().list();        for (Person person : personList) {            Log.d("TAG", "person:" + person.getName() +                    person.getId() + person.getSex()                    + person.getAge());        }    }}

本人菜鸟一个,大神勿喷,有什么不对的地方希望大家指出评论,希望大家一起努力学习进步!

1 0
原创粉丝点击