Android / ORMLite插入行ID [英] Android/ORMLite Insert Row with ID

查看:168
本文介绍了Android / ORMLite插入行ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用ORMLite在Android上使用SQLite数据库。作为这个的一部分,我从后端服务器下载一组数据,我想要将这些数据添加到SQLite数据库中的完全相同的格式,它是在后端服务器(即ID是相同的,等) 。



所以,我的问题是,如果我填充我的数据库条目对象(我们称为设备),包括设备的generatedId /主键字段通过setId ,然后我运行DAO.create()与该设备条目将该ID正确保存?我试过这样的方式,在我看来,这不是这样。如果是这种情况,我会再试一次,并寻找其他问题,但与前几个代码我不能找到一个。所以基本上,如果我调用DAO.create()在一个数据库对象的ID集合将该ID发送到数据库,如果不是,我如何插入一个主键值已经填写的行? p>

谢谢!

解决方案

@Femi是正确的, a generated-id 一个id,但。问题不仅在于ORMLite如何存储对象,而且还必须匹配数据库生成的模式。



ORMLite支持 allowGeneratedIdInsert = true 选项 @DatabaseField 允许此行为的注释。



对于后代,你也可以创建共享同一个表的2个对象 - - 一个与生成的id和一个没有。然后你可以使用生成的id Dao来获取该行为,而其他Dao采用由调用者设置的id值。这里是另一个回答,谈论。你的问题听起来像是会创建很多额外的DAO。



唯一的另一个解决方案是不是使用id你的目的。让数据库生成id,然后为您的目的外部设置一个您使用的附加字段。在某些情况下强制数据库ID在我看来是一个不好的模式。


I'm currently using ORMLite to work with a SQLite database on Android. As part of this I am downloading a bunch of data from a backend server and I'd like to have this data added to the SQLite database in the exact same format it is on the backend server (ie the IDs are the same, etc).

So, my question to you is if I populate my database entry object (we'll call it Equipment), including Equipment's generatedId/primary key field via setId(), and I then run a DAO.create() with that Equipment entry will that ID be saved correctly? I tried it this way and it seems to me that this was not the case. If that is the case I will try again and look for other problems, but with the first few passes over the code I was not able to find one. So essentially, if I call DAO.create() on a database object with an ID set will that ID be sent to the database and if it is not, how can I insert a row with a primary key value already filled out?

Thanks!

解决方案

@Femi is correct that an object can either be a generated-id or an id, but not both. The issue is more than how ORMLite stores the object but it also has to match the schema that the database was generated with.

ORMLite supports a allowGeneratedIdInsert=true option to @DatabaseField annotation that allows this behavior. This is not supported by some database types (Derby for example) but works under Android/SQLite.

For posterity, you can also create 2 objects that share the same table -- one with a generated-id and one without. Then you can insert using the generated-id Dao to get that behavior and the other Dao to take the id value set by the caller. Here's another answer talking about that. The issue for you sounds like that this will create a lot of of extra DAOs.

The only other solution is to not use the id for your purposes. Let the database generate the id and then have an additional field that you use that is set externally for your purposes. Forcing the database-id in certain circumstances seems to me to be a bad pattern.

这篇关于Android / ORMLite插入行ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆