You are here: Platform Specific Issues > Web Environment > Spring MVC Example

Spring MVC Example

This example is a tiny CRUD application which shows how to use db4o in a web-application. This example uses the Spring MVC framework. Of course, db4o works with any webframework. Download the code here. This example uses Maven to build and find the dependencies. You can use a Maven plugin for your favorite IDE in order to open the project.

Managing Object Containers

It uses the code from the servlet-example to have a object container for each request. On each new request a object container is opened. Then all operations are done on the container. When the request ends, the container is closed.

You also can use the features of your web framework or your dependency injection framework to archive the same goal.

Object Identification

This example uses a GUID for each object to identify it across requests. Persisted objects which inherit from the IDHolder class which contains the id-field. Take a look at alternatives for ids. See "Comparison Of Different IDs"

Using db4o

You can use db4o as expected. In this example we use a the db4o-container of the request:

@RequestMapping(value = "list.html", method = RequestMethod.GET)
public ModelAndView get() {
    ObjectSet pilots = db4o.objectContainer().query(Pilot.class);
    return new ModelAndView("list", "pilots", new ArrayList<Pilot>(pilots));
}
HomeController.java: List all pilots on the index-page

Using IDs

Now the ids can be used in the views and controllers to identify objects. For example in a list-view you use the ids for the edit- and delete-links:

<c:forEach items="${pilots}" var="pilot">
    <tr>
        <td>
            <a href="edit${pilot.id}.html"/>Edit</a>
            <a href="delete${pilot.id}.html"/>Delete</a>
        </td>
        <td>
                ${pilot.name}
        </td>
        <td>
                ${pilot.points}
        </td>
    </tr>
</c:forEach>
list.jsp: In the view use the ids to identify the objects

Another location where the ids are used is in the controllers. For example when you need to store changes. First we get a object which contains all changes. Then we copy all changes to the existing object in the database and finally store it. See "Merging Changes"

@RequestMapping(value = "/edit{id}.html", method = RequestMethod.POST)
public ModelAndView editPilot(@PathVariable final String id, Pilot pilotFromForm) {
    Pilot pilotFromDatabase = db4o.objectContainer().query(new Predicate<Pilot>() {
        @Override
        public boolean match(Pilot p) {
            return p.getId().equals(id);
        }
    }).get(0);
    pilotFromDatabase.setName(pilotFromForm.getName());
    pilotFromDatabase.setPoints(pilotFromForm.getPoints());
    db4o.objectContainer().store(pilotFromDatabase);
    return new ModelAndView(new RedirectView("list.html"));
}
HomeController.java: Update the object