Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GreenDao primary key on multiple columns

I am using greendao to maintain SQL database on Android. Right now I am facing a problem of generating entity with two columns as primary key. To be clear I have column1 and column2 both of them are Long values and they together form a primary key.

I tried to model it as

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

but it is not working. I am getting unique constrain failed when trying to insert and when trying to inserOrReplace it simply replaces based on column1 id.

like image 913
horin Avatar asked Nov 18 '16 13:11

horin


People also ask

Can we apply primary key on multiple columns?

A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

How do you declare multiple columns as primary key?

For defining a PRIMARY KEY constraint on multiple columns, use the SQL syntax given below. CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID, NAME) );

Can 3 columns be a primary key?

For a constraint to be recognized as a primary key, it must contain unique values throughout the row and none of the values must be NULL. In a table, there can only be one primary key. A primary key can have one or as many columns as possible.

What type of primary key has multiple columns defined?

A composite key specifies multiple columns for a primary-key or foreign-key constraint. The next example creates two tables. The first table has a composite key that acts as a primary key, and the second table has a composite key that acts as a foreign key.


2 Answers

I have solved it by defining entity like this:

@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 that this probably isn't best solution but it is working. However bounty is still open and I will give it to anyone who can give me better solution.

like image 120
horin Avatar answered Oct 13 '22 00:10

horin


GreenDao doesn't support composite primary keys as you might expect.

Issue 26 was opened on the github project regarding this, and Issue 476 references it too.

You can try and work around it by having an ID for the primary key which references additional properties, but this won't allow you to set a unique restriction on your fields so you will have to validate yourself.

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

like image 39
Eddie Curtis Avatar answered Oct 13 '22 01:10

Eddie Curtis