Creating foreign key constraints in ORMLite under SQLite

时光毁灭记忆、已成空白 提交于 2019-11-29 12:01:53

问题


As it is not possible to add foreign keys using an "ALTER TABLE" statement in SQLite, I am stuck on how to configure my database to enforce valid foreign keys, or perform cascaded deletes without explicit code overhead.

Anybody got an idea how to accomplish this with ORMLite under SQLite?


回答1:


how to configure my database to enforce valid foreign keys, or perform cascaded deletes without explicit code overhead.

ORMLite supports a columnDefinition="..." field in the @DatabaseFiled annotation @Timo. I'm not sure if it provides you the power you need but it does allow you to have custom column definitions.

http://ormlite.com/javadoc/ormlite-core/com/j256/ormlite/field/DatabaseField.html#columnDefinition()

If it doesn't then I'm afraid that you may have to create your database outside of ORMLite in this case. You can use TableUtils.getCreateTableStatements() to get the statements necessary to create the table and add the enforcement and cascade statements that you need. Here are the javadocs for that method.




回答2:


To elaborate on Gray's awesome answer (for anyone else who stumbles upon this question), you can use the columnDefinition annotation to define a foreign key constraint and cascading delete.

First, foreign key constraints were added to SQLite in 3.6.19, which means you can use them in Android 2.2 or higher (since 2.2 ships with SQLite 3.6.22). However, foreign key constraints are not enabled by default. To enable them, use the technique from this answer.

Here's an example using the columnDefinition annotation. This assumes your table/object you are referencing is called parent which has a primary key of id.

@DatabaseField(foreign = true,
      columnDefinition = "integer references parent(id) on delete cascade")
private Parent parent;

Note that the format for the String value does not include the column name (that's what the columnName annotation is for).




回答3:


I think the next link can be helpful:

http://mueller.panopticdev.com/2011/03/ormlite-and-android.html

in short, you can set it as :

public class Person {
...
@DatabaseField(columnName = "organization_id", canBeNull = false)
private Organization m_organization;

This way, Person has a foreign key to Organization, and the key it uses on Organization is "organization_id" .

Hope this helps.



来源:https://stackoverflow.com/questions/6090075/creating-foreign-key-constraints-in-ormlite-under-sqlite

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