7

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.

horin
  • 1,664
  • 6
  • 23
  • 52

2 Answers2

5

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.

horin
  • 1,664
  • 6
  • 23
  • 52
3

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

Eddie Curtis
  • 1,207
  • 8
  • 20
  • 5
    I was able to add unique constraints to fields by doing the following. For an example where we want a `customer` table to have unique restriction on both first and last name fields (bad in practice but just an example) you put information in the `@Entity` annotation (GreenDao 3) like this: `@Entity(nameInDb = "customer",indexes = { @Index(value = "firstname,lastname", unique = true)})` – Carl Poole Feb 17 '17 at 22:30
  • This is the best solution so far and it works perfectly. Greendao Entity modelling says the same. http://greenrobot.org/greendao/documentation/modelling-entities/#crayon-5949da361cc17011493334 – xrnd Jul 05 '17 at 08:15