9

I'm using ormlite for Android and I'm trying to get a multiple column unique-constraint. As of now i'm only able to get a unique constraint on indiviudal columns like this:

CREATE TABLE `store_group_item` (`store_group_id` INTEGER NOT NULL UNIQUE ,
    `store_item_id` INTEGER NOT NULL UNIQUE ,
    `_id` INTEGER PRIMARY KEY AUTOINCREMENT );

and what I want is

CREATE TABLE `store_group_item` (`store_group_id` INTEGER NOT NULL ,
    `store_item_id` INTEGER NOT NULL ,
    `_id` INTEGER PRIMARY KEY AUTOINCREMENT,
    UNIQUE( `store_group_id`, `store_item_id` );

In my model I've been using the following annotations for the unique columns:

@DatabaseField( unique = true )

Is there a way to get this to work?

Gray
  • 115,027
  • 24
  • 293
  • 354
Pzanno
  • 2,185
  • 2
  • 20
  • 23

2 Answers2

14

How about using

@DatabaseField (uniqueCombo = true) 
String myField;

annotation instead - is it a matter of the uniqueIndexName being faster when accessing items in the table?

Ready4Android
  • 2,022
  • 2
  • 25
  • 29
  • This is the right answer if you have version >= 4.20 which was added 4/30/2011. http://ormlite.com/changelog.txt. Good find! – Pzanno Aug 22 '11 at 21:03
  • Oh thanks :) but like I said - maybe Gray could clarify if there is a performance catch to this. – Ready4Android Aug 25 '11 at 23:10
7

Edit:

As @Ready4Android pointed out, we've since added in version 4.20 support for uniqueCombo annotation field. Here are the docs:

http://ormlite.com/docs/unique-combo

There should be no performance differences between using this mechanism versus the uniqueIndexName mentioned below.


Yes. You can't do this with the unique=true tag but you can with a unique index.

@DatabaseField(uniqueIndexName = "unique_store_group_and_item_ids")
int store_group_id;
@DatabaseField(uniqueIndexName = "unique_store_group_and_item_ids")
int store_item_id;

This will create an index to accomplish the unique-ness but I suspect that the unique=true has a hidden index anyway. See the docs:

http://ormlite.com/docs/unique-index

I will look into allowing multiple unique fields. May not be supported by all database types.

Gray
  • 115,027
  • 24
  • 293
  • 354