Joda with JPA

I have to work with a few legacy databases that are used by several different apps (apparently the database is a perfect integration point), and I want to use the Joda api in my persistence. In this example the date is actually stored as a string, genius! I’m going to use LocalDate as the string doesn’t store the time element. If you are lucky enough and the database is actually storing date time check this post out Joda With DateTime

To start with a create a simple helper class that converts String to LocalDate and LocatDate to String

public static LocalDate createLocalDateForString(String dateString){
  DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
  return StringUtils.isEmpty(value) ? null :  fmt.parseDateTime(dateString).toLocalDate();	
}
    
    public static String createStringForLocalDate(LocalDate date){
    	return date.toString("yyyyMMdd"); 
    }

Next is to create your own user type. This is done by implementing org.hibernate.usertype.UserType. The main methods I’m implement are

public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		LocalDate result = null;
		String dateAsString = rs.getString(names[0]);
		if(!rs.wasNull()){
			result = StringUtils.isNotEmpty(dateAsString) ? DateHelper.createLocalDateForString(dateAsString) : null;
		}
		return result;
	}

public void nullSafeSet(PreparedStatement statement, Object value, int index)
			throws HibernateException, SQLException {
		if(value == null){
			statement.setNull(index, SQL_TYPES[0]);
		}else{
			String dateAsString = DateHelper.createStringForLocalDate((LocalDate)value);
			statement.setString(index, dateAsString);
		}
}

All that is left is to add the annotation to each of your entity properties that you want to use as LocalDate.

@org.hibernate.annotations.Type(type = "xxx.LocalDateUserType")
Advertisements

Please ! Stop using floating point numbers for financial data

Again and again I see developers using doubles for storing financial data (e.g. monetary figures, interest rates etc.). This always causes some sort of rounding issue down the line.

try this in your IDE:

double total = 0;
for (int i =0; i < 10; i++){ total += 0.1; } System.out.println(total); [/source] If you expect the answer to be 1 or 1.0, then you're wrong ! Question: are you writing a game ? Answer: no; then use an effing BigDecimal! Grrr...

Using Hibernate Search in SEAM 2.0 Application

I implemented hibernate search recently in a SEAM project I was working on. I wanted to use the excellent suggestion tag from the excedel library and I wanted to use an index rather than hitting the database for each of the searches. I also wanted to use wildcard searches and for each keystroke this would be far to expensive. To implement it I completed the following steps: –

In my persistence.xml I added the following to the properties of my persistence-unit:-

<property name="hibernate.search.default.indexBase" value="PATH TO YOUR INDEX DIRECTORY"/>
<property name="hibernate.ejb.post-insert" value="org.hibernate.search.event.FullTextIndexEventListener"/>
<property name="hibernate.ejb.post-update" value="org.hibernate.search.event.FullTextIndexEventListener"/>
<property name="hibernate.ejb.post-delete" value="org.hibernate.search.event.FullTextIndexEventListener"/>

The path of your index base can be anywhere you want as long as the application has permission to write to it.

To used hibernate search you need to identify and highlight all of the classes that you want to search, you also need to identify each of the properties that you want indexed and the indexing strategy, you can find out what the various types are here Hibernate Search

@Indexed(index="index_direcory")
public class SomeClass

@Field(index=Index.TOKENIZED, analyzer = @Analyzer(impl = LowerCaseAnalyser.class))
@Column(name = "inv_name", length = 200, nullable = true)
private String name;

Inject an instance of FullTextEntityManager into your code. I used a stateless session bean that was used throughout the application

@In
private FullTextEntityManger entityManager;

I used a three different query types, RegEx, Prefix and WildCard.

RegexQuery(new Term(fieldName,".*[^-'\\w]" + searchString.toLowerCase() + "(\\s|$)"));
PrefixQuery(new Term(fieldName,searchString.toLowerCase()));
WildcardQuery(new Term(fieldName,'*'+searchString.toLowerCase()+'*'));

The regex one was used to search for firstname surname i.e. Jo Bloggs. The prefix query was used to search for Jo* i.e. Joanne, Jo Bloggs. The wildcard one, the most expensive one, was used to search for *Jo* i.e. Jones, BillyJoBloggs. The fieldname is the obviously the name of the field, so in:-

@Field(index=Index.TOKENIZED, analyzer = @Analyzer(impl = LowerCaseAnalyser.class))
private String name;  

FiledName would = name

All that is left to do it actually query the index and this is done by:

entityManager.createFullTextQuery(query,SomeClass.class).getResultList();

This has been in production for a some time now and it’s been stable and performed well. There has only been one instance to date of the index getting screwed up but I catered for that and enable the index to be rebuilt. I also had to provide this as any update to the indexed fields via direct sql wouldn’t be updated.

Calling Stored Procedures in JPA

Recently I had to call a stored procedure using JPA and to my surprise I soon found out that it’s not directly supported. So how do you call a stored procedure? My stack is

Db = Sybase
AppServer = JBoss 4.2.3
Java = 1.6
Persistance = EJB3 implemented by Hibernate
Hibernate = 3.4.0.GA

So the first thing I do is to create a named native query on my entity which looks something like this:

@NamedNativeQuery(name="StoredProc_Call",
                  query="stored_proc_name(:param1, :param2, :param3)",
                  hints={
                      @QueryHint(name = "org.hibernate.callable",value = "true"), 
                      @QueryHint(name = "org.hibernate.readOnly",value = "true")
                  },
                  resultSetMapping="scalar", resultClass=Result.class)

@SqlResultSetMapping(name="scalar",columns=@ColumnResult(name="result")

Because I’m using hibernate as my EJB3 implementation, the default for JBoss, I can use it to call the stored proc for me using the hints attribute which takes in an array of queryhint objects.

Because native scalar results aren’t supported by EJB3 you also have to set the resultClass and the resultSetMapping.

@SqlResultSetMapping(name="scalar",columns=@ColumnResult(name="result")

All that is required now is to create the native query, set the required parameters and call it.

Query query = entityManager.createNamedQuery("StoredProc_Call");

Non-anaemic models and service oriented architectures

The term “anaemic domain model” is used to describe an entity layer that contains very little business logic. Typically in this architecture, the business logic is contained in services and/or delegates. There are several problems with this approach:

  • Business logic quickly gets scattered and duplicated across the system
  • It is difficult to maintain because it is hard to determine which class needs to be changed
  • It is difficult to test because the service/delegate usually has many dependencies
  • It is not particularly object oriented (e.g. polymorphism, which can reduce a lot of complexity by reducing ‘type-logic’, is rare)

The trend these days is towards Domain Driven Design (DDD), and is a strategy against anaemic domain models. In this architecture, services are used as an ‘anti-corruption-layer’ to translate requests from the external domain to the internal domain of the system. The majority of the logic is contained within the domain model (this includes persistent and non-persistent objects).

When developing a non-anaemic model (e.g. DDD), it is tempting to call services directly to perform logic (to perhaps an external system, or send a message), to hide complexity from the client:

class Account {
    Balance getBalance() {
        for(Transaction t : getTransactionService().getTransactions(…)){
            //… sum them up
        }
    }

    TransactionService getTransactionService() {
        // lookup service
    }
}

I think this not good design for a number of reasons:

  • The risk of Leaky Abstraction (e.g. having to declare checked Exceptions to methods)
  • Generally speaking, the domain model doesn’t have enough information about the nature of the method call to perform well. The service would be better suited to know how the model will be used (e.g. in a loop).
  • It is harder to test the business logic because you’ve got to mock out too many dependencies.
  • I believe that entities should be deterministic, the behaviour must be determinable given the state of the system/database.
  • Potentially introduces circular dependencies between service->model->service->model etc. which causes problems for maintainability, testing and debugging.

So how do we have a nice, clean, rich domain model ? One way is to pass an implementation of an interface to the domain (e.g. a delegate to a service) so the domain can perform its logic:

class Account {
    Balance getBalance(TransactionRepository repos) {
        // … get the transactions, sum them up
    }
}
// Getting the balance on a single account
Account account =...;
account.getBalance(singleAccountTransactionRepository);
// Getting the balance on many accounts
List<Account> accounts = ...;
for(Account account : accounts){
          account.getBalance(allAccountTransactionRepository);
}

The idea here is that you substitute the most appropriate implementation to get the best performance for the particular use case.

There is a subtle difference between the two, but the second IMO is a cleaner, more-flexible solution.

Re: A general approach to exceptions in Java

My previous post about exceptions in Java begs the question: Where do so called “business exceptions” fit in with all of this?

Business Exceptions are Checked Exceptions

Following on from my reasoning, the user is something that you have no control over. Therefore you expect these types of exceptions to occur. Making them checked exceptions forces you to handle them in some way.

A classic example of these errors are validation errors. These should be checked exceptions because usually you’d need to force the user to fix the entered data before the form can be submitted.

Dealing with Checked Exceptions

The problem of checked exceptions is: how do you handle them ? You’ve got to catch them somewhere (or rethrow), how do you know what to do with them ? This is usually a requirements question; this should be a hint to you to go back to the business and get some clarification on the requirements.

Persistent Strategies

I’ve just finished working on a cash management system. The core of what the system does is listen to messages produced by various sources and record a transaction (i.e. a debit and a credit) between two accounts.

For example, the system will listen to trade messages produced by our trading system and charge a trade fee to the client. This involves debiting the client and crediting the Fee house account.

This seems innocent enough, but to create a transaction you must have a reference to each of these accounts.

The client’s account is easy enough to find as all the required information is supplied in the trade message. But what about the house account ? How does the system find an instance of the house Account ?

One could do something like this, store the account number in a constant somewhere:

Account account = accountService.getAccount(FEE_HOUSE_ACCOUNT_NUMBER);

// create Transaction with client and house account

This is pretty bad IMO because there is duplication and “hard coding” ( even if it is in a properties file) of what house account numbers there are.

If you didn’t want to store the account number in code (or in a properties file which is almost as bad) you could add it to the static data for that transaction type:

@Entity
class TransactionType {
    String name;
    Account creditAccount; // this could be null to indicate that the account is based on the message
    Account debitAccount; // this could be null to indicate that the account is based on the message
    //...
}

then you would just find the TransactionType and the get the credit or debit account.

This would work, but it is very specific, since sometimes we may want to find the debit / credit account in a different way (e.g. “find the loan account associated with the client’s cash account”).

Enter the Persistent Strategy.

Basically, the idea is that rather than store links directly to Accounts in your static data, store a Strategy to obtain the right Account.

@Entity
public class TransactionType {</code>

    private String type;

    @ManyToOne
    private AccountAllocationStrategy toAccountStrategy;

    @ManyToOne
    private AccountAllocationStrategy fromAccountStrategy;
}

@Entity
@Inheritance
public abstract class AccountAllocationStrategy {
    public abstract Account getAccount(Transaction transaction);
}

What we’ve done is added a strategy for find the from / to account and we can have specific implementations:

@Entity
public class FixedAccountAllocation extends AccountAllocationStrategy {

    @ManyToOne
    private Account account;

    public Account getAccount(Transaction transaction) {
        return account;
    }
}

@Entity
public class InvestorAccountAllocation extends AccountAllocationStrategy {

    @Override
    public Account getAccount(Transaction transaction) {
        return transaction.getInvestorAccount();
    }
}

(there are a few more implementations I’ve left out for brevity).

You could achieve a similar effect by using a code of some sort (e.g. an enum) to denote the strategy and look up the strategy instance via Spring, but I like this better since it is more transparent and doesn’t require involving other frameworks. The major problem with the Spring approach is you’ve still got to specify the account numbers somewhere in your Spring context file which is duplication (once in the Spring file, once in the database) which, we all know, is bad :)

It might seem like abusing entities or the domain model but it is a really powerful pattern. Think of these entities as your rule domain. JPA makes mapping entities really easy and the number of strategies are finite so you can be quite creative in your mapping and inheritance hierarchies. You can also fully cache the strategy entities so performance will not be an issue.

We use this pattern in a few places in the system and it has made the code much cleaner and maintainable.