Skip to content

AutoMappers

Muhammad Hewedy edited this page Nov 9, 2017 · 10 revisions

spwrap is not a mapping library, it allow you to easily and simply call stored procedures but delegates mapping the result set and output parameters to you.

Spring frameworks spring-jdbc module and Apache commons-dbutil provides auto-mapping for result sets into custom domain object.
spwrap can depend on either of these libraries to provide auto-mapping for the result set (output parameters are not supported).

So, if your project classpath has either of these libraries (precedence for spring-jdbc if both are on the classpath), so you can use the annotation @AutoMapper that will delegate the mapping to one of them.

Example:

Customer is a regular java domain object (that doesn't implement any interface):

public class Customer {
    private Integer id;
    private String firstname, lastname;

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

And you can define your DAO method like:

@AutoMapper
@StoredProc("list_customers")
List<Customer> listCustomers3();

see the full demo application

NOTE: This code will throws CallException if spwrap couldn't find either spring-jdbc or commons-dbutils on classpath

NOTE: From spring docs about BeanPropertyRowMapper "Please note that this class is designed to provide convenience rather than high performance. For best performance, consider using a custom RowMapper implementation."

NOTE: @AutoMappers cannot mixed with regular @Mappers or @Scalars, in fact the three cannot mixed with each other.

In case of spring-jdbc, spwrap uses BeanPropertyRowMapper to map multi-column result sets, and SingleColumnRowMapper to map single-column result sets.
And in case of commons-dbutils, spwrap uses GenerousBeanProcessor to map to map multi-column result sets, and just uses rs.getObject(1) to map single-column result sets.

Remember, custom Mappers gives you better performance and more control.

I recommend using the AutoMappers if you have a Result set of 1 column for example:

@AutoMapper
@StoredProc("list_customer_names")
List<String> listCustomerNames();

this is because you cannot make String implement ResultSetMapper, so you have no option but create a custom class that implements the ResultSetMapper and feed it via @Mapper(MyCustomStringListMapper.class).

Use @Scalar when you have a single output parameter and @AutoMapper when you have a single-column result set.