[Learning persistence]

Let's create a simple persistent object - User and let's add some fields.

public class User extends DBPersistentObject{
    public void define() {
        addField("FirstName"new VarcharField(50));
        addField("LastName"new VarcharField(50));
        addField("Age"new IntField());
    }
}

VarcharField is a class that implements a type corresponding to SQL VARCHAR(n).
IntField is another class that implements a type corresponding to SQL INT.
Almost all SQL standard types were implemented. Also notice that field names are joint That's because the field name will be used as column name in the SQL table that holds our User objects.

Use this code snippet to understand how persitent ojects are created, saved and loaded:

System.out.println("Creating a new persistent object ...");
User user1 = new User();
System.out.println("Saving into the database ...");
user1.save();
System.out.println("Creating another persistent object ...");
User user2 = new User();
System.out.println("Setting fields ...");
user2.set("FirstName","William");
user2.set("LastName","Blake");
System.out.println("Saving into the database ...");
user2.save();
System.out.println("Loading object from database ...");
User user3 = (UserDBPersistentObject.loadObject(user2.getID());
System.out.println("First Name = " + user3.get("FirstName"));
System.out.println("Last Name = " + user3.get("LastName"));

Now let's make a form for adding new users and editing info about existing ones:

public class DemoUserForm extends AbstractForm{
    public void define() {
        setType(Types.get("tutorial.persist.User"));
        addObjectField("FirstName").setDescription("First Name");
        addObjectField("LastName");
        addObjectField("Age");
    }
}

Here's the result:

Pay attention to the URL - that's how you should call it for adding a new User. When you'll fill in the fields and will press Submit - the new User will be saved automatically.

This form can also be used to edit info about existing users. You can do it like this :

That's right - all that you need is to pass the ID of the User to the form as parameter. Pay attention again to the URL.

For successful compiling of tutorial examples you should add persistence.jar to CLASSPATH.
persistence.jar is located in /WEB-INF/lib.

Previous page Tree of contents Next page