DB-Aware Annotations

back to index

Dynject comes with support for db-aware annotations, which are annotations that interact with a database. For example, the @DBExists annotation makes sure that the stored value in a property exists in the database, while the @DBLookup annotation allows you to perform a lookup considering the value of a property as a primary key and retrieving some dependant value (for example, if an HTTP request is coming with a "uk" value, but you want to have "UnitedKingdom" stored in the property, where the association between both is expressed in some database table). If you are using JPA, Dynject can do even more for you, by fetching complete entities from the underlying data store based on their primary key, and flagging nonexistant entities as validation errorrs

A very simple example could look like this:

@DBAware(jdbcConnectionString="jdbc:mysql://localhost/test?user=dbaware&password=dbaware")
public class Customer {
  @DBLookup(
    entityName="countries",
    searchIn="countryId",
    replaceWith="countryName",
    ifNotFound=NotFoundPolicy.ASSIGN_NULL
  )
  private String country;

  @DBLookup(
    entityName="cities",
    searchIn="zip",
    replaceWith="cityName",
    ifNotFound=NotFoundPolicy.ADD_ERROR
  )
  private String city;

...
}

So now if you do:

ErrorMap errors = Shell.assign(customer, "country","us");

The country property will be assigned with "United States" instead of "us". Of course, it gets better if you combine this feature with the ability to automatically read Struts, HTTP parameters or Swing fields.

In the above example, the @DBAware annotation is using a JDBC connection string in order to connect to the database. However, this is not the recommended way and certainly there are more alternatives. The @DBAware annotation can instruct db-aware annotations to get their connection: