如何在Play框架中更新对象?

MrR*_*ROY 3 java model edit save playframework

如何编辑数据库中的现有对象?例如,如果我有一个像这样的模型: class Topic{title,content,author},当我编辑和保存对象时,我不想再次添加“作者”对象。如何更新现有对象而不是添加新对象?

and*_*kus 5

如果您是从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.
Run Code Online (Sandbox Code Playgroud)

我就是那样做的。取决于您拥有多少字段,此代码将很快变得笨拙。绝对把它放在一个方法中。另外,请参见此处有关findByID()和其他从数据库中提取对象的方法。