开发者

How to do multiple column unique-constraint in ormlite ( SQLite )

开发者 https://www.devze.com 2023-02-16 15:02 出处:网络
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:

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?


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号