GreenDao初体验

GreenDao初体验进行时
- 添加java包,GreenDao需要三个jar包,此处用2.1版本示例
1. 首先添加代码生成所需要的jar,不过这个是java程序,需要写的添加在Module的build.gradle文件中

dependencies {
    ...
    compile 'de.greenrobot:greendao-generator:2.1.0'
}
  1. 主工程中引入其他两个操作数据库的jar
dependencies {
    ...

    compile 'de.greenrobot:greendao-generator:2.1.0'
    compile 'de.greenrobot:greendao:2.1.0'

}
  1. 准备工作完成,接下来对象创建以及关联了,接着在Module项目中创建一个java程序,代码如下:
  public static void main(String[] args) throws Exception {
        // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。
        // 两个参数分别代表:数据库版本号与自动生成代码的包路径。
        Schema schema = new Schema(1, "com.database");
//      当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示:
//      Schema schema = new Schema(1, "me.itangqi.bean");
//      schema.setDefaultJavaPackageDao("me.itangqi.dao");

        // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。
        // schema2.enableActiveEntitiesByDefault();
        // schema2.enableKeepSectionsByDefault();

        // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。

        addAll(schema);
//        addConfig(schema);
//        addGroup(schema);
//        addDispose(schema);
//
//        addDevice(schema);
//        addGroup_Device(schema);
        // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录(既之前创建的 java-gen)。
        // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。
        new DaoGenerator().generateAll(schema, "E:/wyw/studio/1219/testDemo/app/src/main/java-gen");
  1. 实体内容如下所示

    private static void addAll(Schema schema) {
        /*存储对象   id  nickName(名称)  address(配置地址)   wifi_id;*/

        /**总配置表*/
        Entity note = schema.addEntity("ConfigBean");
        note.addLongProperty("configId").primaryKey();
        note.addStringProperty("address");
        note.addStringProperty("nickname");
        note.addLongProperty("w_ID");

        /**组表*/
        Entity gnote = schema.addEntity("GroupBean");
        gnote.addLongProperty("groupId").primaryKey();
        gnote.addStringProperty("nickname");


        /**音量部署dispose,该信息包含了具体的音响进度控制*/
        Entity dnote = schema.addEntity("DisposeBean");
        //配置部署id
        dnote.addLongProperty("disposeId").primaryKey();
        //主音量
        dnote.addIntProperty("ch1");
        dnote.addIntProperty("ch2");
        dnote.addIntProperty("master");







        /**设备表,现在想一下,是设备一对多的管,也就是一个设备多个配置,但是一个配置只有一个设备,相当于设备是顾客,订单是配置*/
        Entity sound = schema.addEntity("DeviceBean");
        sound.addLongProperty("deviceId").primaryKey();
        //设备名称
        sound.addStringProperty("nickname");
        //设备地址
        sound.addStringProperty("address");


        //--------------------------------------------------------------------------------------------

        /**
         * 建立配置组关系【一对多关系】
         */
        /**通过组管理【也即最开始的配置】*/
        Property property3 = gnote.addLongProperty("configId").getProperty();//组中添加管理id
        gnote.addToOne(note, property3);//一个组对应一个管理配置
        note.addToMany(gnote, property3).setName("groups");//一个配置中添加一个组列表


        /**
         * 建立组和配置的关系,一个组对应多个配置,通过配置也可查询组,组有上下级的配置   还有平级的配置[已舍弃,用第二种方法],此处指的是上下级【一对多关系】
         */
        /**通过组查找配置,一对多,一个组对应多个配置*/
        Property property2 = dnote.addLongProperty("groupId").getProperty();//设备配置中添加组id
        dnote.addToOne(gnote, property2);//一个配置对应一个组信息
        gnote.addToMany(dnote, property2).setName("disposes");//一个组中多个设备配置信息



        /**建立设备与配置之间的关系*/
        Property property = dnote.addLongProperty("deviceId").getProperty();//配置中添加设备id
        dnote.addToOne(sound, property);//一个配置中一个设备,相当于把设备写到配置中去,通过设备id,关联设备
        sound.addToMany(dnote, property).setName("disposes");//一个设备中存在多个配置,通过设备id,查询多个配置


    }
  • 数据库关系如下所示image
    1. 运行程序,在目录:E:/wyw/studio/1219/testDemo/app/src/main/java-gen 下面会生成我们的数据库程序,吧代码剪切到主项目中
    2. 接下来就是各种数据库操作了,首先在Application中写一些初始化代码,如下:
/**
 * Created by wangyawen on 2017/4/20 0020.
 */
public class App extends Application {

    private static App mInstance;
    private static final String DB_NAME = "xx-dbs";
    private static DaoMaster mDaoMaster;
    private static DaoSession mDaoSession;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        if (mInstance == null)
            mInstance = this;
    }

    public static DaoMaster getDaoMaster(Context context) {
        if (mDaoMaster == null) {
            DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
            SQLiteDatabase db = openHelper.getWritableDatabase();
            mDaoMaster = new DaoMaster(db);
        }
        return mDaoMaster;
    }

    ;

    public static DaoSession getDaoSession(Context context) {
        if (mDaoSession == null) {
            if (mDaoMaster == null) {
                getDaoMaster(context);
            }
            mDaoSession = mDaoMaster.newSession();

        }
        return mDaoSession;
    }

}
  1. 然后是数据库操作的帮助类


/**
 * Created by wangyawen on 2017/4/12 0012.
 * 数据库管理类
 */
public class Presenter {


    DaoSession daoSession;



    //总配置管理【包含设备】
    ConfigBeanDao configDao;
    //设备调试管理
    DisposeBeanDao disposeDao;
    //组配置
    GroupDisposeDao groupDisposeDao;
    //组管理
    GroupBeanDao groupDao;
    //设备管理
    DeviceBeanDao deviceDao;

    private static Presenter instance;
    private static Context appContext;

    private Presenter() {
    }


    public static Presenter getInstance(Context context) {

        if (instance == null) {
            instance = new Presenter();
            if (appContext == null) {
                appContext = context.getApplicationContext();
            }

            instance.daoSession = App.getDaoSession(context);
            instance.configDao = instance.daoSession.getConfigBeanDao();
            instance.disposeDao = instance.daoSession.getDisposeBeanDao();
            instance.groupDao = instance.daoSession.getGroupBeanDao();
            instance.deviceDao = instance.daoSession.getDeviceBeanDao();
            instance.groupDisposeDao = instance.daoSession.getGroupDisposeDao();
        }


        return instance;
    }




    //-------------总配置操作----------------------------------

    /**
     * 增加一条配置信息
     *
     * @param bean
     * @return
     * @throws Exception
     */
    public long add(ConfigBean bean) throws Exception {
        return configDao.insertOrReplace(bean);
    }

    /**
     * 修改配置
     *
     * @param note
     * @throws Exception
     */
    public void update(ConfigBean note) throws Exception {
        configDao.update(note);
    }

    /**
     * 查询所有配置
     *
     * @return
     * @throws Exception
     */
    public List<ConfigBean> loadAll_cf() throws Exception {
        return configDao.loadAll();
    }

    /**
     * 删除某一条配置
     *
     * @param note
     * @throws Exception
     */
    public void delete(ConfigBean note) throws Exception {
        configDao.delete(note);
    }


    //-------------------组操作-----------------------------

    /**
     * 添加一个新组
     *
     * @param bean
     * @return
     * @throws Exception
     */
    public long add(GroupBean bean) throws Exception {
        return groupDao.insertOrReplace(bean);
    }

    /**
     * 修改组信息
     *
     * @param note
     * @throws Exception
     */
    public void update(GroupBean note) throws Exception {
        groupDao.update(note);
    }

    /**
     * 删除组
     *
     * @param note
     * @throws Exception
     */
    public void delete(GroupBean note) throws Exception {
        groupDao.delete(note);
    }


    //-------------------------------配置【也即设备显示】操作-----------------------------------------------------

    /**
     * 增加配置,配置中包含设备
     *
     * @param bean
     * @return
     * @throws Exception
     */
    public long add(DisposeBean bean) throws Exception {
        return disposeDao.insertOrReplace(bean);
    }


    /**
     * 编辑配置【包含设备信息】
     *
     * @param note
     * @throws Exception
     */
    public void update(DisposeBean note) throws Exception {
        disposeDao.update(note);
    }

    /**
     * 删除配置
     */
    public void delete(DisposeBean note) throws Exception {
        disposeDao.delete(note);
    }

   //------------------关系操作----------------------------------------------
    /**
     * 通过类别id,获取当前大配置
     *
     * @return
     */
    public ConfigBean getConfigInfoType(long configId) {
        return configDao.load(configId);
    }

    /**
     * 获取组
     *
     * @param configId 配置id
     * @return
     */
    public List<GroupBean> getGroupsByTypeId(long configId) {
       //清除缓存
        daoSession.clear();
        return getConfigInfoType(configId).getGroups();
    }

    /**
     * 获取设备配置
     *
     * @param configId 配置id
     * @return
     */
    public List<DisposeBean> getDisposeByTypeId(long configId) throws Exception {
        daoSession.clear();
        return getConfigInfoType(configId).getDisposes();
    }


    /**
     * 获取组类别信息
     */
    public GroupBean getGroupInfoType(long groupId) {
        return groupDao.load(groupId);
    }

    /**
     * 获取设备配置
     *
     * @param groupid 组id
     * @return
     */
    public List<DisposeBean> getdisposeByTypeId(long groupid) {
        GroupBean bean = getGroupInfoType(groupid);
        /*清除缓存,重新进行查询*/
        daoSession.clear();
        return bean.getDisposes();
    }

    /**
     * 获取配置类别信息
     */
    public DisposeBean getdisposeInfoType(long disposeId) {
        return disposeDao.load(disposeId);
    }


    /**
     * 查询设备【通过配置】
     *
     * @param disposeId 配置id
     * @return
     */
    public DeviceBean getDeviceById(long disposeId) {
        return disposeDao.load(disposeId).getDeviceBean();

    }

    /**
     * 根据类别id获取设备
     *
     * @param deviceId
     * @return
     */
    public DeviceBean getdeviceInfoType(long deviceId) {
        return deviceDao.load(deviceId);
    }


//---------------------设备增加-------------------------

    /**
     * 增加设备
     *
     * @param bean
     * @return
     * @throws Exception
     */
    public long add(DeviceBean bean) throws Exception {
        return deviceDao.insertOrReplace(bean);
    }

    /**
     * 通过地址查询设备
     *
     * @param mac
     * @return
     * @throws Exception
     */
    public DeviceBean getDevice(String mac) throws Exception {
        DeviceBean bean = deviceDao.queryBuilder().where(DeviceBeanDao.Properties.Address.eq(mac)).build().unique();
        return bean;

    }

  • [x] 从大配置中查询组做一下示例,代码是这样的


   /**
     * 获取组
     *
     * @param configId 配置id
     * @return
     */
    public List<GroupBean> getGroupsByTypeId(long configId) {
       //清除缓存
        daoSession.clear();
        return getConfigInfoType(configId).getGroups();
    }
  • 发现可以直接通过ConfigBean对象进行获取,没有必要专门写一个查询语句去数据库表里查询,直接通过get方法就能够拿到,当然首先需要获取配置,不然会直接报这个异常,如下:
throw new DaoException("Entity is detached from DAO context");

    /**
     * 通过类别id,获取当前大配置
     *
     * @return
     */
    public ConfigBean getConfigInfoType(long configId) {
        return configDao.load(configId);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值