Methods

The Record class provides the methods for create, update, and delete operations.

Creating Objects

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 Model class:

  1. From the drop-down list box at the top of Code Editor, choose Playground.

    ../../_images/code-editor.png

    Caution

    To avoid unintentionally changing existing code in your project, make sure that the Code Editor is set to PLAYGROUND.

  2. To test the example User class code, 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();
   }
}
  1. 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.

Updating Objects

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 user name, 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;
   }
}

Deleting Objects

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");
    }
 }