Wednesday, April 28, 2010

MongoDB with Sculptor - Data Mapper

This post is part of a series of articles describing the support for MongoDB in Sculptor. This post explains how the mapping between domain objects and MongoDB data objects is performed.

When working with mongoDB Java API the DBObject plays a central role. It is like a key value Map. Values can be of most types and also collections and other DBObjects for nested documents. Sculptor also adds support for Enums and Joda date time classes.

Implementing mapping of domain objects to DBObjects is a tedious and error prone programming task that is a perfect candidate for automation. Sculptor comes in handy for this. Sculptor generates data mapper classes that converts domain objects to DBObjects. It is useful to not have to write those mappers by hand.

An early definition of a BlogPost in the blog sample might look like this in Sculptor model:

Entity BlogPost {
String slug key
String title
String body
}


From this Sculptor generates domain object class in java with appropriate getters, setters, constructors, equals, etc. Sculptor also generates a mapper for converting the BlogPost to/from DBObject. The generated code looks like this:


public DBObject toData(BlogPost from) {
if (from == null) {
return null;
}

DBObject result = new BasicDBObject();

if (from.getId() != null) {
ObjectId objectId = ObjectId.massageToObjectId(from.getId());
result.put("_id", objectId);
}

result.put("slug", from.getSlug());
result.put("title", from.getTitle());
result.put("body", from.getBody());

return result;
}


and in the other direction:


public BlogPost toDomain(DBObject from) {
if (from == null) {
return null;
}

String slug = (String) from.get("slug");

BlogPost result = new BlogPost(slug);

if (from.containsField("_id")) {
ObjectId objectId = (ObjectId) from.get("_id");
String idString = objectId.toStringMongod();
IdReflectionUtil.internalSetId(result, idString);
}

if (from.containsField("title")) {
result.setTitle((String) from.get("title"));
}
if (from.containsField("body")) {
result.setBody((String) from.get("body"));
}

return result;
}


I'm happy that I don't have to write and especially maintain that kind of code. The generation is not a one time shot. When you change the model the domain objects and the mappers are regenerated.

Domain objects can of course also have behavior, otherwise it wouldn't be a rich domain model. The behavior logic is always written manually. Separation of generated and manually written code is done by a generated base class and manually written subclass, a gap class. It is in the subclass you add methods to implement the behavior of the domain object. The subclass is also generated, but only once, it will never be overwritten by the generator.

You might need to add some hand written code to customize the mappers. That is easy. In the model you can specify that you need a subclass that you can implement yourself. This is very useful for doing data migration.

It can also be good to know that fields marked with transient are are not stored, but they are loaded if they exist in the retrieved documents. This can also be used for data migration.

By default the names in the data store are the same as the names in the Java domain objects. In case you need to use other names it is possible to define that in model with databaseTable and databaseColumn.


Entity BlogPost {
databaseTable="BlogEntries"
String slug key
String title
String body databaseColumn="content"
}


You have probably selected MongoDB for its low latency. Then you want the data mapper to be fast also. The mappers provided by Sculptor are generated code that runs at full speed. Alternative solutions using reflection or intermediate String JSON format is probably not as fast.

Tuesday, April 27, 2010

MongoDB with Sculptor - Introduction

MongoDB bridges the gap between key-value stores (which are fast and highly scalable) and traditional RDBMS systems (which provide rich queries and deep functionality).

Would you like to?
  • Use a rich persistent domain model à la DDD with automatic mapping to MongoDB data structures.
  • Use associations even though the underlaying data store is not relational.
  • Express queries in refactoring safe terms of the domain model.
  • Get CRUD operations, and GUI, for free.
Then you should try Sculptor with the brand new MongoDB target implementation.

In the next few days I will describe the features one-by-one, but first an brief overview of what Sculptor provides for efficient development of a typical enterprise or web application with MongoDB as persistent store.

Sculptor is a productivity tool that let you express your design intent in a textual DSL, from which Sculptor generates high quality Java code and configuration. Read more in What is Sculptor?

Sculptor generates data mapper classes that converts domain objects to/from MongoDB data structures, DBObjects.

Sculptor provides generic repository operations for use with MongoDB. This includes operations such as save, delete, findById, findByKey, findByCondition, and some more.

Queries can be expressed with a slick fluent api that support code completion and refactoring.

Rich support for associations. Aggregates are stored as a embedded documents. Other associations are stored with referring ids. In the domain objects there are generated getters that lazily fetch associated objects from the ids. This means that you don't have to work with the ids yourself, you can follow associations as usual.

A sample blog application may look like this when defined in Sculptor textual DSL:


Visualization, generated by Sculptor, of the above model looks like this:


Read the other posts that describes the features in more detail:

More hands on instructions of how to use Sculptor is available in the Sculptor MongoDB Tutorial.

Wednesday, March 31, 2010

Support for mongoDB started

I think NoSQL datastores are a very interesting complement to relational databases. I think mongoDB is a good choice for the rich persistent domain models that are typical for a Sculptor application. Today's article at InfoQ about mongoDB mention the relation between document stores and DDD.

We have started prototyping and it looks promising. The idea is that that Sculptor will provide:
  • Access objects (implementation of repository operations) that interact with mongoDB.
  • Good query support (e.g. findByCondition).
  • Automatic mapping between domain objects and mongoDB documents (DBObject) will be generated.
  • Different types of association will be supported. Aggregates are typically embedded documents and other associations are stored as id references. Maybe we will provide a mechanism to lazy load associated documents.

Saturday, March 20, 2010

Improved Graphviz Visualization

I have improved the visualization with several new features. You can use this new diagram generator right away as described in the end.

Several diagrams with different focus and level of detail are generated. Below are samples of the different types of diagrams. You can click on the images below to see them in full scale.

Module dependencies:

Overview:


One separate diagram for each module:


Diagram with focus on elements marked as core domain (hint="umlgraph=core"). Note that core domain objects also have another font color (and background color) in all diagrams.


And finally, a diagram with full detail of all objects.


All colors can be configured using generator properties file and it is also possible to set the color for individual elements using a hint in model file (hint="umlgraph.bgcolor=FFCC99"). It is also possible to hide elements using hint="umlgraph=hide".

You can generate the new diagrams in your Sculptor project right away. Version 1.8.1-SNAPSHOT includes this, but even if you need to use an older version (not snaphot) you can drop in the new generator templates in your project. Download from trunk
umlgraphhelper.ext to your src/main/resources/extensions/ and
UMLGraph.xpt to your src/main/resources/templates/

To generate images (png) from the generated Graphviz dot files you can use the new fornax-graphviz-m2-plugin. Add the following to your pom.xml:


<plugin>
<groupId>org.fornax.toolsupport</groupId>
<artifactId>fornax-graphviz-m2-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals><goal>run</goal></goals>
</execution>
</executions>
</plugin>

You also need to install the excellent Graphviz tool.

Thursday, March 11, 2010

Success Story - Using my Own Tool

I’m the founder and lead developer of Sculptor. Why would I write a success story? They should be written by users. Right, I’m a user of my own tool. This is maybe the key to why the tool is working as good as it does.

Since May 2009 I have been working with a customer in the logistics business. I’m involved in several projects but in my “main” project we develop a Track & Trace system. We receive events with parcel state information from several production systems in different countries. Volumes around 500 million tracking events during 6 months, which is the period we need to support track&trace searching.

In this department JEE was greenfield development. They have been using Java before, but not with application servers and modern frameworks. We established guidelines and tools for the new platform.

The introduction of Sculptor started with a technical prototype of the domain model. About 20 entities were developed in 2 days. Test driven. Of course this was only an initial draft, but it was important to quickly be able to try our ideas in practice. We have done a lot of refactoring of the domain model since then and Sculptor doesn’t sit in the way for doing changes. It simplifies change.

When evaluating Sculptor for the prototype my team developers stressed the importance of being able to remove the tool and continue without starting from scratch. It was good to see that the developers were able to quickly grasp the concepts and be able to use the tool immediately without any lengthy education.

When I and the other developers in my team had used Sculptor for a while another team wanted to try it also. I helped with converting existing code. The conversion and initial learning was smooth.

We listed the following benefits of using Sculptor for all new projects at the department:
  • Improved productivity. Generate code from high level description. Less manual mistakes. Relieved the developers from repeating and tedious programming tasks.
  • High quality of generated code. As if written manually, but better. We actually found several flaws in the hand written code when converting it to Sculptor.
  • Consistent design and structure. The department was running several projects in parallel, with different developers, and varying experience of JEE. Consistency between solutions was considered very important from a maintenance perspective.
  • Easy to learn. The developers that tried Sculptor found it intuitive to use. “It’s nothing magic”.
  • Great possibilities for customization. We did some adjustments to fit the database naming conventions.
  • Good design. The design of the generated code match our guidelines, JEE, JPA, DDD.
  • Easy to remove the tool. No dynamic runtime magic.
We have continued to use Sculptor successfully. We use Sculptor for all new projects. Several new developers have joined the teams and quickly learnt how to use Sculptor. We are 11 developers in 4 projects right now.

Sunday, February 21, 2010

Bonus Material

For my customer's project I created a small addition to Sculptor, that might be useful for you also. The domain model is important for communication, and we need to document it. The difficult thing with documentation is to keep it up to date with changes. Placing the descriptions close to the code makes it easier to do the changes to the documentation at the same time as when you change the code. Since we use Sculptor it was a natural choice to write the descriptions in the model file and generated the documentation.

"A location is our model is stops on a journey, such as cargo
origin or destination, or carrier movement endpoints."
Entity Location {
not optimisticLocking
- @UnLocode unLocode key
'Actual name of this location, e.g. "Stockholm"'
String name not changeable

Repository LocationRepository {
@Location find(@UnLocode unLocode) throws LocationNotFoundException;
findAll;
protected findByKeys;
}
}



From the model we generate HTML documentation of all domain objects including their attributes and associations.



Try it if you like. It is easy to understand and adjust to fit your needs.

Download this generation template and place it in src/main/resources/templates/
In SpecialCases.xpt you add

«AROUND templates::Root::Root FOR Application»
«targetDef.proceed()»
«EXPAND DomainModelDoc::start»
«ENDAROUND»


The generated result is located in src/generated/resources/DomainModelDoc.html

Tuesday, February 16, 2010

Sculptor 1.8.0 Released

Only two weeks after the big 1.7.0 we are happy to deliver another major release - 1.8.0. This time it is no new functionality, but the usability of DSL editor is much, much better.

We have migrated from openArchitectureWare 4.3.1 to Xtext/Xpand/MWE 0.7.2 at Eclipse.org. Many thanks to Todd Ferrell for doing most of this migration.

Now, content assist (ctrl+space) works as you would expect.

Another useful feature is formatting (pretty printing) of model files (ctrl+shift+F).

Watch the DSL editor in action in the demo below, or even better try it yourself.