GreenDao primary key on multiple columns

I am using greendao to support SQL database on Android. Now I am faced with the problem of creating an object with two columns as a primary key. To be clear, I have column1 and column2, both of which are long values ​​and together form the primary key.

I tried to simulate it as

@Index(unique = true) private Long column1, column2 

but it does not work. I get a unique constraint when trying to insert, and when trying to insertOrReplace it just gets replaced based on the identifier column1.

+5
source share
2 answers

I solved this by defining an object as follows:

 @Id(autoincrement = true) //I totally don't care about value of this field private Long idLocal; @Index //this are 2 columns that I use as primary key private Long column1id, column2id; 

I know this is probably not the best solution, but it works. However, the generosity is still open, and I will give it to everyone who can give me a better solution.

+5
source

GreenDao does not support composite primary keys, as you might expect.

Issue 26 was discovered in the github project about this, and Issue 476 also refers to it.

You can try and work around it with a primary key identifier that refers to additional properties, but this will not allow you to set a unique restriction on your fields, so you have to check yourself.

See also http://greenrobot.org/greendao/documentation/modelling-entities/#Primary_key_restrictions

+3
source

Source: https://habr.com/ru/post/1259972/


All Articles