Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to annotate a default value inside a android room entity?

I couldn't find any information how to annotate a SQL - "DEFAULT" value while looking into the @ColumnInfo docs for the new Android Persistence Library.

Does Room even provide an annotation for default values?

My current solution would be to manually create the corresponding Table ...

CREATE TABLE MyTable (   ...   MyDefaultValuedCol  TEXT DEFAULT 'Default Value',   MyDefaultFlagCol    INT  DEFAULT 1 ) 

... and put Room on top.

@Entity(tableName = "MyTable") class MyClass {     ...      public String MyDefaultValuedCol;      public boolean MyDefaultFlagCol;  } 
like image 824
Rüdiger Avatar asked Dec 20 '17 12:12

Rüdiger


People also ask

What is an entity in Android?

android.arch.persistence.room.Entity. Marks a class as an entity. This class will have a mapping SQLite table in the database. Each entity must have at least 1 field annotated with PrimaryKey . You can also use primaryKeys() attribute to define the primary key.


2 Answers

With the release of room persistence 2.2.0, there's a new property added to @ColumnInfo annotation which can be used to specify the default value of a column. See documentation.

@Entity(tableName = "users") data class User(     @PrimaryKey val id: Long,     @ColumnInfo(name = "user_name", defaultValue = "temp") val name: String     @ColumnInfo(name = "last_modified", defaultValue = "CURRENT_TIMESTAMP" ) val lastModified: String ) 
like image 186
Ahsan Saeed Avatar answered Sep 20 '22 12:09

Ahsan Saeed


Room hasn't any annotation for default value, but you can set default value in your entity like this:

@Entity(tableName = "MyTable") class MyClass {     ...      public String MyDefaultValuedCol = "defaultString";      public boolean MyDefaultFlagCol = true;  } 
like image 34
AliSh Avatar answered Sep 19 '22 12:09

AliSh