SQLite 下在 ORMLite 中创建外键约束
由于无法在 SQLite 中使用“ALTER TABLE”语句添加外键,因此我陷入了如何配置数据库以强制执行有效外键,或在没有显式代码开销的情况下执行级联删除的问题。
有人知道如何在 SQLite 下使用 ORMLite 实现这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了详细说明 Gray 的精彩答案(对于任何其他偶然发现这个问题的人),您可以使用
columnDefinition
注释来定义外键约束和级联删除。首先,外键约束在 3.6.19 中添加到 SQLite,这意味着您可以在 Android 2.2 或更高版本中使用它们(因为 2.2 随 SQLite 3.6.22 一起提供)。但是,外键约束默认情况下不启用。要启用它们,请使用此答案。
以下是使用
columnDefinition
注释的示例。这假设您引用的表/对象称为parent
,其主键为id
。请注意,字符串值的格式不包括列名称(这就是 columnName 注释用于)。
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 calledparent
which has a primary key ofid
.Note that the format for the String value does not include the column name (that's what the columnName annotation is for).
ORMLite 支持
@DatabaseFiled
注释 @Timo 中的columnDefinition="..."
字段。我不确定它是否为您提供了所需的功能,但它确实允许您拥有自定义列定义。如果没有,那么我担心您可能必须在 ORMLite。您可以使用 TableUtils.getCreateTableStatements() 获取创建表所需的语句并添加所需的强制和级联语句。这里是 该方法的 javadocs。
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.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.我认为下一个链接可能会有所帮助:
http://mueller.panopticdev。 com/2011/03/ormlite-and-android.html
简而言之,你可以将其设置为:
这样,Person就有了Organization的外键,它在Organization上使用的键是“organization_id” 。
希望这有帮助。
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 :
This way, Person has a foreign key to Organization, and the key it uses on Organization is "organization_id" .
Hope this helps.