如何编辑数据库中的现有对象?例如,如果我有这样的模型:
class Topic{title,content,author}
,当我编辑并保存对象时,我不想再次添加“作者”对象。如何更新现有对象而不是添加新对象?
最佳答案
如果您继承自 Model 类(您应该这样做),它会提供一个 save()
方法和一个 ID 属性。当您对从数据库中获取的对象调用 save()
时,它将被更新,如果您对新对象调用它,它将被保存到数据库中。这一切都是自动的!
仅更新特定字段
Model.save()
保存整个对象,因此如果您只想更新对象中的某些数据字段,您首先必须构建您想要进入数据库的确切对象。因此,假设您不想使用 Topic(id, content, author)
对象更新空字段:
Topic newT = Topic(1L, 'yyy', null);
Long id = newT.getID();
Topic oldT = Topic.findByID(id); //Retrieve the old values from the database
Author newAuthor = newT.getAuthor(); //null
if (newAuthor != null) { //This test will fail
oldT.setAuthor(newAuthor); //Update the old object
}
String newContent = newT.getContent(); //Not null
if (newContent != null) {
oldT.setContent(newContent); //Update the old object
}
// Now the object oldT holds all the new, non-null data. Change the update tests as you see fit, of course, and then...
oldT.save(); //Update the object in the database.
我就是这样做的。根据您拥有的字段数量,这段代码会很快变得非常笨重。一定要把它放在一个方法中。另外,see here about findByID()以及其他从数据库中提取对象的方法。
关于java - 如何更新游戏框架中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7543391/