BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Polyforms - Reduce DAO Code Duplication

Polyforms - Reduce DAO Code Duplication

This item in japanese

Bookmarks

The goal of the Polyforms project is to remove the heavily duplicated glue code to tie data access objects to the underlying persistence API. The approach used in the framework is to automatically implement service methods on a Repository interface defined by the developer. Methods defined on the interface are, by default, linked to database operations via naming conventions. For example, the wiki discusses how to implement a repository for a User entity object. First, the API for the repository must be defined:

public interface UserRepository extends EntityRepository<User, String> {
       
    @Finder
    List<User> findByCreator(User creator);
}

The @Finder annotation marks the method for Polyforms. Rather than creating an implementation for the UserRepostiory, however, a matching Hibernate query needs to be provided on the User entity via another annotation.

@NamedQueries({
    @NamedQuery(name = "User.findByCreator", query = "select u from User u where u.creator = :creator"),
})
public class User {
   
...
}

As per the documentation, the convention used to find queries is based on the method name, as well as the name of the entity itself:


The rule for mapping method with Named Query is [name of Named Query] = [name of Entity].[name of method]. you can specify the name of Named Query in @Finder as @Finder("findUserByName"), then the name of Named Query will be "User.findUserByName".

In addition to the @Finder annotation, there is also an @Updater and a @Counter annotations to provide support for mass updates and counting queries respectively. The

EntityRepository

parent interface already provides support for saving single entities, deleting, and retrieving by identifier.



All of this wiring is done via the

Spring framework

and relies on Spring aspects to be able to provide runtime implementations of the APIs.



Other functionality supported by Polyforms includes:


  • Automatic management of tracking information (created by, created date, modified by, modified date)
  • Transparent pagination support
  • Definition of transaction boundaries via annotation
  • Domain event model to decouple persistence events from application functionality

More information is available on the

Polyforms wiki

.

Rate this Article

Adoption
Style

BT