Sugar ORM in Android: update a saved object in SQLite

*爱你&永不变心* 提交于 2019-12-06 04:00:00

问题


I'm new to app development using SQLite and Sugar ORM on Android, and have tried to read through the Sugar ORM documentation, but didn't find anything for how to update a saved object in SQLite. Can I still save the object after changing its properties? something like:

Customer myCustomer = (Customer.find(Customer.class, "id = ?", id)).get(0);
myCustomer.setName("new name");
myCustomer.setAddress("new Address");
myCustomer.save(); // is this okay for updating the object?

the save() method won't create another new object while leaving the old entry untouched, right?


回答1:


It will update your entity. The Sugar ORM overwriting your existing e.g Name and updated it with "new name" after the save() method call.




回答2:


Your code should update the row without issue.

From the docs - Update Entity:

Book book = Book.findById(Book.class, 1);
book.title = "updated title here"; // modify the values
book.edition = "3rd edition";
book.save(); // updates the previous entry with new values.



回答3:


Updating a saved object is pretty straightforward.

Retrieve the object;

Object object= Object.findById(Object.class, ID);

Set the attributes you need to;

object.setAttr("new value");

Then finally call save;

object.save();

Alternatively, as someone mentioned above one can choose to use update() which works slightly differently and would ideally be used when changing several attributes;

First create the object and set the necessary attributes;

Object object= new Object();
object.setAttr("some data");

Then set an ID for the Object that ideally already exists in the database in order to target that item for replacement;

object.setID(ID);

And finally;

object.update();



回答4:


Save and Object methods are completely different and both are really useful. If you have an object and you say:

Object.save();

That will override all of the other fields as well for example:

column1       column2
1             1

if in your object you have only set column1 corresponding field a number like 2 you will get:

Object.save();

column1       column2
2             NULL

Object.update();

column1       column2
2             1

You don't need to use .setId() explicitly to get update working it looks for a unique item if it's found it will update that,if not it will create a new row.By default an auto increment ID column is added to each of your tables and used as unique ids for update.If you need your own fields to be unique use:

@Unique
String MyID

or for multiple of the same thing you can use:

@MultiUnique("MyFirstID,MySecondID")
public class MyClass extends SugarRecord {...

which both are name of your fields in the table.



来源:https://stackoverflow.com/questions/26835785/sugar-orm-in-android-update-a-saved-object-in-sqlite

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