You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 8 Next »

Introduction

In the first part of the Blog tutorial, you will learn:

  • How to create a EOModel for the database (we will use H2)
  • How to use migrations to create the database tables
  • How to use ERRest to create blog posts with JSON format and how to display the blog posts in HTML for readers

Create a new project

You will need to create a new project for this tutorial. In Eclipse, open the File menu, select New and select Wonder REST Application. Name your project as BlogRest.

Create the database model

Database structure

We will build a small database model for the blog. The database will have two tables: BlogEntry and Author.

BlogEntry will have the following columns:

Column name

Type

Constraints

id

integer

primary key

title

string(255)

 

content

string(4000)

 

lastModified

timestamp

 

creationDate

timestamp

 

author

integer

relation with Author

Author will have the following columns:

Column name

Type

Constraints

id

integer

primary key

firstName

string(50)

 

lastName

string(50)

 

email

string(100)

unique

passwd

string(16)

 

Creating the EOModel

To create the database, we will first create a EOModel and use migrations to build the database on the file system (H2 will take care of creating the database file).

An EOModel consists of entities, attributes and relationships. When using it in a RDBMS context, an entity is a table (or a view), an attribute is a table column and a relationship is a join between two tables.

To create the EOModel, in the project right-click on the project name and select New -> EOModel.

Name it BlogModel and in the plugin list, select H2. Click Finish.

The model should show up in a window that looks like this:

If it didn't show up, the window might have opened behind the main Eclipse window. If that's the case, open the Window menu and select the windows that have Entity Modeler in its name.

In the Entity Modeler window, click on Default, and for the URL field, type

jdbc:h2:~/BlogTutorial

. When the database will be created, it will be stored in your home directory (/Users/youruser/ on OS X).

Now, right-click on BlogModel and select New Entity.

Type the following details in the Basic tab:

  • Name: BlogEntry
  • Table Name: BlogEntry
  • Class Name: your.app.model.BlogEntry

Now, it's time to add the entity's attributes (aka, the table's columns). You will see that the entity already have an attributed named "id". That attribute is a integer for the primary key. Leave it there.

Let's create the first attribute: the title of the blog entry. Right-click on the entity and select New Attribute. Type the following values:

  • Name: title
  • Column: title
  • Prototype: varchar255

When you use prototypes, you don't need to define the type (varchar, int, etc.) for the database, so by using prototypes, if you switch from a RDBMS system to another one, say from H2 to MySQL, you only need to change the JDBC connection string and bundle the EOF plugin for the RDBMS, no need to switch data types in the model.

Now, repeat the last two steps to create the other attributes for the BlogEntry entity, with the following values:

Attribute name

Column

Prototype

content

content

longtext

lastModified

lastModified

dateTime

creationDate

creationDate

dateTime

If you did everything well, the list of attributes should look like this:

You will notice that the attributes have a column with a lock in it. When a lock is present, it will use the value of that attribute for UPDATE ... WHERE attribute = '' statement. This is to do optimistic locking, aka to prevent data conflict when the data object was modified by two different users. Using timestamps for optimistic locking is not a good idea because for certain RDBMS, the value can be different because of milliseconds, so remove the locks on the lastModified and creationDate attributes. The final list should look like this:

Next step is to create the Author entity. Create a new entity with Author at its name (and also as the table name), and for the class name, use your.app.model.Author. The attributes for this entity are:

Attribute name

Column

Prototype

firstName

firstName

varchar50

lastName

lastName

varchar50

email

email

varchar100

passwd

passwd

varchar16

Final list of attributes should look like this:

Now, it's time to link the two entities together. A Author can have multiple blog entries, and a BlogEntry can only have one author. To create the relationship (the join), right-click on Author and select New Relationship. On your right, select BlogEntry in the list. On your left, select to many BlogEntries, and on your left, select to one Author. Now, in BlogEntry, we need to store the primary key of the author so that we can make the join. The relationship builder allow us to add that attribute, so make sure and a new foreign key named is checked (it is checked by default). The Create Relationship pane should look like this:

If you check in the Outline tab, you should see that Author now have a blogEntries relationship, and BlogEntry have a author relationship.

You are now ready to save the model. Save it (File -> Save) and close the Entity Modeler window. If you open the Sources in the main Eclipse window, you will notice that the Sources folder contains a package named your.app.model.

That package have four Java classes: _Author, Author, _BlogEntry and BlogEntry. Those classes were generated by Veogen, a templating engine build on Velocity. The two classes that starts with a underscore are recreated every time you change the EOModel, so if you want to change something in those classes, you need to change the template (no need for that right now). But you can change freely the two classes that don't have the underscore, and this is what we will be doing.

What we are going to do is to write a simple method that returns the full name of an author, e.g. a method that simply concatenate the first name, a space and the last name of the author. To do so, double-click on Author.java and add the following methods:

public String fullName() {
	  return this.firstName() + " " + this.lastName();
	}

Nothing fancy here. Now, let's use migrations to actually create the database.

Using migrations

Migrations allow you to create the tables and columns (and some types of constraint). Entity Modeler have support to generate the code for the first migration, which is called "migration 0". To do that, open the EOModel (BlogModel EOModel in the Resources folder), right-click on the model name and select Generate Migration.

Copy the generated code in the clipboard. Close Entity Modeler and in the main Eclipse window, right-click on Sources, select New and select Class.

Type your.app.model.migrations as the package and BlogModel0 as the name of the class. Click Finish.

In the Sources folder, open the your.app.model.migrations package, a class named BlogModel0 should be there. Delete everything in that file EXCEPT the first line (which should be package your.app.model.migrations) and paste the code that was generated by Entity Modeler. Save the file.

One last step: migrations are disabled by default. To enable them, you need to uncomment two properties in the Properties file that is located in the Resources folder. Open that file (double-click on it).

Remove the pound char in front of those two properties:

#er.migration.migrateAtStartup=true
#er.migration.createTablesIfNecessary=true

After removing the pound char, the two properties should look like this:

er.migration.migrateAtStartup=true
er.migration.createTablesIfNecessary=true

You are now ready to start the application so that it creates the database! To do so, right-click on Application.java (in the your.app folder) and select Run As -> WOApplication. In Eclipse's Console tab, you should see some output, including something similar to:

BlogRest[62990] INFO  er.extensions.migration.ERXMigrator  - Upgrading BlogModel to version 0 with migration 'your.app.model.migrations.BlogModel0@4743bf3d'
BlogRest[62990] INFO  er.extensions.jdbc.ERXJDBCUtilities  - Executing CREATE TABLE Author(email VARCHAR(100) NOT NULL, firstName VARCHAR(50) NOT NULL, id INTEGER NOT NULL, lastName VARCHAR(50) NOT NULL, passwd VARCHAR(16) NOT NULL)
BlogRest[62990] INFO  er.extensions.jdbc.ERXJDBCUtilities  - Executing ALTER TABLE Author ADD PRIMARY KEY (id)
BlogRest[62990] INFO  er.extensions.jdbc.ERXJDBCUtilities  - Executing CREATE TABLE BlogEntry(authorID INTEGER NOT NULL, content TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, id INTEGER NOT NULL, lastModified TIMESTAMP NOT NULL, title VARCHAR(255) NOT NULL)
BlogRest[62990] INFO  er.extensions.jdbc.ERXJDBCUtilities  - Executing ALTER TABLE BlogEntry ADD PRIMARY KEY (id)
BlogRest[62990] INFO  er.extensions.jdbc.ERXJDBCUtilities  - Executing ALTER TABLE BlogEntry ADD CONSTRAINT "FOREIGN_KEY_BLOGENTRY_AUTHORID_AUTHOR_ID" FOREIGN KEY (authorID) REFERENCES Author (id)
BlogRest[62990] DEBUG NSLog  -  evaluateExpression: <er.h2.jdbcadaptor.ERH2PlugIn$H2Expression: "UPDATE _dbupdater SET version = ? WHERE modelname = ?" withBindings: 1:0(version), 2:"BlogModel"(modelName)>

If you see this and that the application is running (it should open a window in your favorite browser), migration worked and your database have been created, congratulations! You can now stop the application (click the square red button in Eclipse's Console tab) and continue to the next step.

Creating REST controllers and routes

Project Wonder contains a framework called ERRest, which follow the same patterns as Ruby on Rails REST concepts. Using REST-style URLs is perfect for building a public blog and to create REST services to manage posting over HTTP with JSON, XML or other formats.

By default, a REST route in ERRest will generate a link like this:

/cgi-bin/WebObjects/AppName.woa/ra/EntityName/id

So for our case, to get the first blog posting from BlogRest, the URL will look like this:

/cgi-bin/WebObjects/BlogRest.woa/ra/blogEntries/1.html

You can shorten the URL by using mod_rewrite in Apache httpd

.

Creating controllers

ERRest needs controllers to act as a broker between working with the objects and the routes. So let's create a controller for BlogEntry.

Adding the routes

Adding posts and authors with curl

Adding HTML views for blog posts

  • No labels