Question

The Spring documentation states:

"If the last two snippets of code actually existed in the same application, it would make sense to remove the duplication present in the two RowMapper anonymous inner classes, and extract them out into a single class (typically a static inner class) that can then be referenced by DAO methods as needed."

The "last two snippets" in this case are database methods that map the results of their calls using two row mappers with identical logic.

My question is why does the inner RowMapper class need to be static... or does it need to be? I have a service method autowired in my DAO that is used to look up constant values like:

//Returns "USA"
lookupService.getCountryForCountryId(1)

Autowired in the parent class.

Changing my RowMapper definition from:

public static final RowMapper<Order> BASIC_SHALLOW_MAPPER = new RowMapper<Order>() {...}

to

public final RowMapper<Order> BASIC_SHALLOW_MAPPER = new RowMapper<Order>() {
    public Order mapRow(ResultSet rs, int rowNum) {
        ...
        lookupService.getCountryForId(rs.getInt("country_id"));
        ...
    }
}

...allows me to translate that data inside of the rowmapper as shown above. Are there any drawbacks to this approach?

Was it helpful?

Solution

The row mapper class doesn't have to be static. But most often it does not need access to fields of the parent class, in these cases it is more efficient to make it static.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top