Methods
The Record class provides the methods for create, update, and delete operations.
All fields in a Record
-derived object are persisted as a database record when the save
method is called on the object.
To continue with the User
class example, the Dari Code Editor can be used to create User
objects.
To create an instance of a class:
From the list box at the top of Code Editor, choose Playground.
WarningTo avoid unintentionally changing existing code in your project, make sure that the Code Editor is set to PLAYGROUND.To test the example
User
class, overwrite any existing code in the editor with the following:import com.psddev.dari.db.*; import com.psddev.dari.util.*; import java.util.*; import com.psddev.dari.test.User; public class Code { public static Object main() throws Throwable { String[] names = {"Curly", "Larry", "Moe", "Bart", "Homer"}; for (String name : names) { User user = new User(); user.setUserName(name); user.save(); } return Query.from(User.class).selectAll(); } }
- Click Run.
The test code calls the User
setter method for each name in the String array and saves the new object. The test code then calls methods from the Query class to retrieve all User
objects, and the Code Editor displays the JSON results in the right pane.
You can update an existing object by retrieving it from the database, changing field values, then re-saving the object. The following code calls the Query
API to return the User
object with the specified username, changes the name of the user, and saves the object with an updated name.
import com.psddev.dari.db.*;
import com.psddev.dari.test.*;
import java.util.*;
public class Code {
public static Object main() throws Throwable {
String name = "Bart";
User user = Query.from(User.class)
.where("userName = ?", name)
.first();
if (user != null) {
user.setUserName("Bartholomew");
user.save();
}
return user;
}
}
You can delete objects from a database with the delete
method on the Record
class.
To continue with the User
class example, the following code retrieves all User
objects from the database. The code iterates the retrieved objects and deletes the object with the specified user name.
import com.psddev.dari.db.*;
import com.psddev.dari.test.*;
import java.util.*;
public class Code {
public static Object main() throws Throwable {
for (User user : Query.from(User.class).selectAll() ) {
if (user.getUserName().equals("Curly") ) {
user.delete();
return ("Curly deleted");
}
}
return ("Can't find Curly");
}
}