Android的 - 在GreenDao数据库中添加默认值 [英] Android - add default value in GreenDao database

查看:3797
本文介绍了Android的 - 在GreenDao数据库中添加默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下,如果有可能添加默认值当我创建greenDao数据库?

I would like to ask, if there is possibility to add default value when I create greenDao database?

Example:
Property pictureIdProperty = user.addLongProperty("pictureId").getProperty();
Property thumbnailIdProperty = user.addLongProperty("thumbnailId").getProperty();
//and here I need something like this:
//thumbnailIdProperty.setDefault(-1); //there is possible to add 
user.addToOne(picture, pictureIdProperty);
user.addToOne(picture, thumbnailIdProperty, "thumbnail");

当我使用数据库,此表那么就没有必要添加默认值总是在我建立这个模型。

And when I'm using database and this table then there is no need to add default value always when I create this model.

推荐答案

我不相信这是由GreenDAO项目这是当今任何官方的支持,但我有一个想法。 SQLite支持可应用到列 DEFAULT 的表约束。对于例如,低于code座显示了<$ c中的默认值$ C>城市表中的列是桑内斯。

I do not believe there is any official support by the GreenDAO project for this as of today but I have an idea. Sqlite supports the DEFAULT table constraint which can be applied to a column. For example, the code block below shows the default value for the City column in table Persons is 'Sandnes'.

    CREATE TABLE Persons
    (
      P_Id int NOT NULL,
      LastName varchar(255) NOT NULL,
      FirstName varchar(255),
      Address varchar(255),
      City varchar(255) DEFAULT 'Sandnes'
    )

知道SQLite支持的默认的约束,我们可以破解生成的 DAO 类。我将使用<一个href=\"https://github.com/greenrobot/greenDAO/blob/465e2ef056ce2d9b5362e51bdffff8ba6bd0ed64/DaoExample/src-gen/de/greenrobot/daoexample/OrderDao.java\"相对=nofollow> OrderDAO.java 作为一个例子。以下代码段是GreenDAO产生code 创建表 code座:

Knowing sqlite supports the Default constraint, we can hack the generated DAO class. I'll use OrderDAO.java as an example. The below snippet is the GreenDAO generated code create table code block:

    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'ORDERS' (" + //
               "'_id' INTEGER PRIMARY KEY ," + // 0: id
               "'DATE' INTEGER," + // 1: date
               "'CUSTOMER_ID' INTEGER NOT NULL );"); // 2: customerId
    }

现在,我们可以的最有可能的修改此支持 DEFUALT 约束。通过添加上述code座一相关行更改 DEFAULT(-1)

Now we can most likely modify this to support the DEFUALT constraint. Change last relevant line in the above code block by adding DEFAULT(-1).

    "'CUSTOMER_ID' INTEGER NOT NULL DEFAULT(-1));"); // 2: customerId

请注意:当测试这种变化,确保无论是增加你的sqlite的架构版本或使数据库被重新重新安装应用程序。

Note: When testing this change, make sure to either increment your sqlite schema version or re-install your app so the database gets recreated.

这篇关于Android的 - 在GreenDao数据库中添加默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆