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

别等时光非礼了梦想. 提交于 2019-12-22 04:32:16

问题


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?


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/5264305/how-to-do-multiple-column-unique-constraint-in-ormlite-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!