Question

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.

Was it helpful?

Solution

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'
    )

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
    }

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top