Showing posts with label relational database. Show all posts
Showing posts with label relational database. Show all posts

2015-05-31

Advancing Enterprise DDD - Moving Forward

In the last essay of the Advancing Enterprise DDD series, we wrapped up our discussion on immutability, as well as the technical discussion overall. In this essay, we wrap up the series by reflecting on what we've learned, and discussing how to apply these lessons as we move forward.

2015-05-24

Advancing Enterprise DDD - Entities, Value Objects, and Identity

In the previous essay of the Advancing Enterprise DDD series, we saw how we might improve our Domain Driven Design model by making our entity classes immutable. Here, we continue to investigate immutable entities by seeing how this affects one of the core DDD building blocks: the value object.

2015-05-17

Advancing Enterprise DDD - Migrating to Immutability

In the previous essay of the Advancing Enterprise DDD series, we saw difficulties emerge in maintaining intra-aggregate constraints. These difficulties arose due to the mutability of our entities, and the Java collections they use to maintain relationships between entities. We also saw that it would be difficult or impossible to use immutable alternatives within JPA. In this essay, we set aside the constraints of JPA for a moment, and imagine a world where entities are composed of immutable objects.

2015-05-10

Advancing Enterprise DDD - Maintaining Intra-aggregate Constraints

In this essay of the Advancing Enterprise DDD series, we begin look to at immutable objects - a common point of contrast between functional and object-oriented programming approaches. In the last essay, we saw at how MongoDB would be a much better vehicle than RDB for persisting well-shaped DDD aggregates. In this essay, we continue to investigate at the way the tools we use affect our thinking and coding, as we witness the contortions we have to go through to make something as straightforward as an intra-aggregate constraint work in the face of mutability.

2015-05-03

Advancing Enterprise DDD - Documents as Aggregates

In the last few essays of the Advancing Enterprise DDD series, we've taken a look at entity aggregates, and the challenges we face in implementing them well. We've seen a great many techniques we can employ using JPA to mitigate these challenges. In this essay, we step out of the JPA and relational database mindset, and consider modeling aggregates with a document database such as MongoDB.

2015-04-26

Advancing Enterprise DDD - Reinstating the Aggregate


Over the past four essays of the Advancing Enterprise DDD series, we have taken a long, hard look at crafting entity aggregates using JPA, and the challenges that arise. We've seen how to choose our cascades and fetch strategies to match aggregate boundaries as best as possible. And we've learned how to design our entity classes defensively against problems with proxy objects. In this essay, we'll investigate further ways to design aggregates well with JPA. There are two major goals we have here:
  1. Prevent the poor design and implementation - or lack of it! - of entity aggregates in our domain
  2. Help developers think in terms of Domain Driven Design concepts such as aggregates
In an ideal world, the tools we use would do these things for us. In the least, it could help make these things easy for us. But if the off-the-shelf tools don't support what we are trying to do, we can attempt to do it ourselves in our project infrastructure. We can do this by providing a standard set of interfaces and abstract classes to be used throughout the project. And we can write unit tests that enforce constraints that we have difficulty enforcing at the compiler level.

We could use documentation and local conventions and rules to fill some of the gaps. But if any two of the three of the following hold, then I can guarantee you that standards and conventions will not be enough:
  1. There are some junior and mid-level developers on our team
  2. You don't always do rigorous code reviews for everything that gets committed
  3. You sometimes face pressure to produce features on a tight schedule
Here are some specific difficulties, as of yet unaddressed, that we have seen with doing entity aggregates with JPA:
  1. Nothing differentiates an aggregate root from a non-root entity
  2. Nothing prevents a repository class for a non-root entity
  3. Nothing prevents an entity from associating with a non-root entity from another aggregate
  4. Nothing prevents an entity composing with an entity from another aggregate
  5. Nothing differentiates between association and compositions
Entities are typically recognized by the JPA @Entity annotation appearing on the class. On some projects, we'll also define an interface or abstract class that all entities inherit from. We could just as easily make a separate marker interface for aggregates as well. For example:

interface Entity {
}

interface RootEntity extends Entity {
}

We can write a unit test that asserts this by reflectively scanning your project's classes, looking for anything with an @Entity annotation that does not inherit from one of these interfaces.

Now, let's assume we are using Spring Data JPA to implement some basic CRUD repositories. We could provide our own repository interface that enforces the constraint that only aggregate roots have repositories. If our application was called Storefront, we might do it like so:

import org.springframework.data.repository.CrudRepository;

interface StorefrontRepository<R extends RootEntity>
extends CrudRepository<R, Long> {
}

The compiler will not stop a developer from bypassing this interface altogether, but we can write a unit test to make sure it is used. We might scan the project for classes marked with Spring's @Repository annotation, and fail if that class does not implement StorefrontRepository.

That's a good start, but what about distinguishing between associative and compositive relationships, and restricting these relationships to respect aggregate boundaries?

Vaughn Vernon provides a nice solution, both in his book Implementing Domain-Driven Design (see page 359 "Rule: Reference Other Aggregates by Identity"), as well as in the essay Effective Aggregate Design found on his website. In essence, he limits the use of JPA relationship mappings, such as @ManyToOne, @OneToMany, etc., to within a single aggregate. This is accomplished by forcing an explicit repository retrieval when navigating associations between entity aggregates.

Vernon accomplishes this by providing identity value object for each of the aggregate roots. Using the example we developed in The Entity and the Aggregate Root, our Customer would have a CustomerId, implemented something like this:

@Embeddable
public class CustomerId {

    @Column(name = "customer_id")
    private Long customerId;

    public CustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public Long getCustomerId() {
        return customerId;
    }
}

Our association from Order to Customer is represented by the Order knowing the identity of the Customer:

@Entity
public class Order extends RootEntity {

    @Embedded
    private CustomerId customerId;

    // ...
}

A service that needs to navigate from the Order to the Customer would then do so with the help of the CustomerRepository:

Customer customer =
    customerRepository.retrieve(order.getCustomerId());

This is a very valuable technique for making it clear in the minds of developers that they are crossing an aggregate boundary, and will help them organize their code with that in mind. While we have seen in Cascades and Fetch Strategies and Overeager Fetch, we cannot always configure our cascades and fetches to fully cover an aggregate. But with this approach, we can at least assure that cascades and fetches do not leak across aggregate boundaries.

At this point I would humbly suggest that the language of identity above is not ideal. It does make it clear that it is a wrapper for a database ID, but is this really what we want? We are using these value objects within our domain classes, so why not name them in the terms of domain modeling, rather than using database terminology? While we rename CustomerId from above to CustomerAssociation, let's flesh out the example a little further. First off, we can create an interface for the associations to implement:

interface Association<R extends RootEntity> {
    Long getId();
}

Our Customer association would now look something like this:

@Embeddable
public class CustomerAssociation implements Association<Customer> {

    @Column(name = "customer_id")
    private Long customerId;

    public CustomerAssociation(Long customerId) {
        this.customerId = customerId;
    }

    @Override
    public Long getId() {
        return getCustomerId();
    }
}

To keep the association metaphor going, let's add a findByAssociation method to our StorefrontRepository:

public abstract class StorefrontRepository<R extends RootEntity>
implements CrudRepository<R, Long> {

    public R findByAssociation(Association<R> assoc) {
        return findOne(assoc.getId());
    }
}

Now our services can follow the association like so:

Customer customer = customerRepository.findByAssociation(
    order.getCustomerAssocation());

This all looks great, but what's to prevent a developer from creating a direct relationship to another aggregate root? The construction below remains entirely legal:

@Entity
public class Order extends RootEntity {

    @ManyToOne(fetch = FetchType.LAZY, cascade = {})
    private Customer customer;

    // ...
}

There's no way we can turn this into a compiler error, so we resort to the next best thing: unit test. Our unit tests run on quite a regular basis, so even if the compiler allows the above example, the mistake will not go unnoticed for long. Here is some pseudocode for a test that will do the job:
  • Use classpath scanning to iterate over all the entity classes in the domain.
    • Use reflection to iterate over all the fields tagged with annotations such as @OneToMany.
      • If the type of the field is a sub-type of RootEntity, then fail.
There's still one question that we haven't answered yet: How do we prevent an entity from forming a compositional relationship with an entity from another aggregate? At the moment there is nothing preventing us from doing something like this:

@Entity
public class Customer extends RootEntity {

    @ManyToOne(fetch = FetchType.LAZY, cascade = {})
    private OrderItem orderItem;

    // ...
}

To prevent things like this, we can make use of F-bounded polymorphism, which is a common enough technique in Scala, but might seem a little strange to a Java programmer. The first thing we do is to modify our Entity interface to specify the root of the entity aggregate as a type parameter:

public interface Entity<R extends RootEntity<R>> {
}

This causes ripples throughout the code developed so far, starting with RootEntity. This is where the F-bounded polymorphism comes in:

public interface RootEntity<R extends RootEntity<R>>
extends Entity<R> {
}

The outcome of this use of type parameters is to force a RootEntity sub-type to specify itself as R. In essence, it prevents us from saying that a Order belongs to the aggregate that has an Customer as root. Trying to do this will give a compiler error about a type bounds mismatch:

// does not compile!
public class Order implements RootEntity<Customer> {
}

We need to modify all our entity classes to specify their root:

public class Customer implements RootEntity<Customer> {
}

public class Order implements RootEntity<Order> {
}

public class OrderItem implements Entity<Order> {
}

We also need to adjust our type signatures for associations and repositories:

interface Association<R extends RootEntity<R>> {
}

public abstract class 
StorefrontRepository<R extends RootEntity<R>>
implements CrudRepository<R, Long> {
}

Now we can write a unit test to prevent the example above, where Customer established a @ManyToOne with an Order Item. We simply scan our entity classes for fields annotated with JPA @ManyToOne, @OneToOne, etc., and then use reflection to assure that the root of the entity class is the same as the root of the referenced entity.

As we've seen today, reflective, classpath scanning unit tests can be a great way to enforce project constraints that are difficult or impossible to enforce at the compiler level. We've also developed a great little framework for enforcing the basic constraints of DDD aggregation in a Java EE application using JPA. This is quite a bit of local infrastructure to develop for the sake of assuring that our entity aggregates are well formed. You could make use of some or all of it to assist your team in designing aggregates well. How far you choose to go will depend on the needs of your team.

If, however, you are in the planning stages of a new project, I would urge you to consider alternatives to JPA and relational database technologies that might be better suited to doing Domain Driven Design. In the next essay, we will investigate how much easier implementing aggregates might be if we switched to MongoDB, or some other document database.

2015-04-19

Advancing Enterprise DDD - Problems with Proxies

In the previous two essays of the Advancing Enterprise DDD series, (Cascades and Fetch Strategies, and Overeager Fetch), we've seen how JPA makes use of proxy objects to represent entities that have not yet been loaded from the database. In this essay, we will take a look at some of the problems raised by the use of proxy domain objects in JPA, and discuss what we can do to avoid them. We'll look at LazyInitializationExceptions, and problems arising from hidden network I/O in general. And we'll look at accidental access to the zeroes and nulls in a proxy object, and unexpected behavior when type-checking our domain object.

2015-04-12

Advancing Enterprise DDD - Overeager Fetch

In the previous essay in the Advancing Enterprise DDD series, we investigated how to tailor our cascades and fetch strategies to align with aggregate boundaries. In this essay, we continue to look at fetch strategies in situations where the shape of our aggregates are more complex.

2015-04-05

Advancing Enterprise DDD - Cascades and Fetch Strategies

In the last essay of the Advancing Enterprise DDD series, we learned about entity aggregates, and how to construct them while doing domain modeling. In this essay, we begin to look at some specifics of how to implement aggregates using JPA. Specifically, we want to configure our cascades and fetch strategies so that persistence operations align with aggregate boundaries.

2015-03-29

Advancing Enterprise DDD - The Entity and the Aggregate Root

In this essay of the Advancing Enterprise DDD series, we will leave behind the POJO for a bit, and look at entity aggregates. After the entity, the aggregate is probably the most important building block in Domain Driven Design. Aggregates provide a way to organize your entities into small functional groups, bringing structure to what might otherwise be a knotted jumble of entity classes.

2015-03-22

Advancing Enterprise DDD - Rethinking the POJO

In the previous essay of the Advancing Enterprise DDD series, we looked at a sample POJO with a variety of un-encapsulated persistence concerns. Unfortunately, this exposure occurs right at the heart of our software system: the domain model. Because the domain classes are used throughout the service layer, and are sometimes mirrored through the application layer up to the user interface, our whole codebase is susceptible to misuse of these data. Furthermore, having these data in the domain classes themselves inevitably clouds our thinking when trying to work in terms of the domain and the ubiquitous language. 

2015-03-15

Advancing Enterprise DDD - The POJO Myth

This is the third essay in my Advancing Enterprise DDD series, where we discuss doing Domain Driven Design with the standard enterprise Java toolset: Java, Spring, Java Persistence API (JPA), and a relational database (RDB).

In the last essay, we took a higher level view of the design principles of JPA. In this essay, we examine how the JPA-annotated plain-old Java object (POJO) fails to separate persistence-level concerns from our domain classes.

2015-03-08

Advancing Enterprise DDD - What Makes It So Hard?

This is the second essay in my Advancing Enterprise DDD series, where we discuss doing Domain Driven Design with the standard enterprise Java toolset: Java, Spring, Java Persistence API (JPA), and a relational database (RDB).

In the previous essay, we reflected on the way the tools we use can affect the way we reason about our domain. In this essay, we look at the high-level design principles of JPA, and how well they align with the principles of DDD.

2015-03-01

Advancing Enterprise DDD - Working with the Tools We Have

We’ve done our best to do Domain Driven Design with the standard enterprise Java toolset: Java, Spring, Java Persistence API (JPA), and a relational database (RDB). While this has been a very successful stack for us in developing enterprise applications, we’ve encountered problems doing DDD well in this environment. In this series of essays, we will look at some of the difficulties we’ve had, and consider ways to improve our situation. We provide advice for doing DDD with the given toolset. And we look ahead to how we might do DDD better with different tooling - specifically, replacing Java with Scala, and RDB with a document database such as MongoDB.