How do I edit an existing object in the database? For example, if I have a model like this:
class Topic{title,content,author}, when I edit and save the object I do not want to add the "author" object again. How do I update my existing object rather than adding a new one?
If you're inheriting from the Model class (as you should), it provides a save() method as well as an ID attribute. When you call save() on an object you got out of the database, it will be updated, and if you call it on a new object it will be saved to the database. It's all automagical!
Model.save() saves the whole object, so if you want to update only some data fields in your object, you first have to construct the exact object you want to go in your database. So let's say you don't want to update null fields, using your Topic(id, content, author) object:
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.
That's how I would do it. Depending on how many fields you have this code is going to get really clunky really fast. Definitely put it in a method. Also, see here about findByID() and other ways to pull objects from the database.
If you look at the JPA Object Binding part of the documentation, you will see it explains that, if you pass in an object to your controller, containing an ID, the object is first automatically loaded from the database, and then the new fields passed in are added to the object.
This means, you can simply call the save() method.
So, you controller action could be something like
public static void editTopic(Topic topic) {
topic.save();
//...any post edit processing
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With