Wednesday, September 3, 2014

JDBC via Spring

Almost every kind of application uses data repository. In most cases it is a relational database, which presents us with object-relational mapping problem. Although there are a lot of solutions, more or less "professional", today I want to show you the simplest way in Java to do this - using JDBC...
...but with Spring!
Image from: http://projects.spring.io/spring-framework/

Many of you will probably ask: "Why should I do that?". Yeah I know - we have Hibernate, JPA and many other libraries to connect to our DB, which do the object-relational mapping for us. Anyway, there are few reasons (in some situations) to choose JDBC over f.e. Hibernate.

1. You want more control

There are many tricks to control the code generated by Hibernate (or other JPA implementation).  However, it is still generated. Of course you can use @NamedQuery or hql directly, but if you use Hibernate that way all the time, it is the right moment to think if you really need such a powerful solution.

2. You have to use what you've got

Everyone wants to work with new projects, but as we all know, most of the time we have to work with something which already exists. Sometimes we have just a standard POJO model with many additional fields, which is used everywhere in application. Adding another domain model persistence, (sometimes with new, alternative connection pool) is just too much work. Many different types of OR mapping in one project also doesn't sound good.

3. Your project is too small

Well... you could kill a mosquito with .45 magnum but sometimes the newspaper is just enough. There is nothing to complain about.

4. Your project business logic is complicated or it's going to change fast

Sometimes your project has to get data from already existing data source.  Sometimes client doesn't know exactly what he really wants. One week you decide to use Hibernate because there are only few simple selects from table, next week you have to join another 42 tables, views and so on (in the worst case you have to re-generate your mapping again and again). SQL logic could be really complicated and the POJO which you get afterwards could make you cry. In case of that you may want to store your business logic in stored procedures. Of course you can use Hibernate to call them, but once again: magnum? really?

I have to admit that I'm a fan of ORM frameworks (especially Hibernate), so I don't believe I wrote something like that. Let's leave this for now, time to write some code. Imagine that we build simple Java SE application with Spring via Maven. We are gonna to use some relational database (to simplify it'll be H2). Here are the dependencies from POM:

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.6.RELEASE</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.180</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.0.1</version>
        </dependency>

And resource's configuration:

            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>

As you can see we've got only Spring libraries, database driver and some commons from apache (we'll use it to build simple data source object for Spring). Time for Spring configuration. It will be an applicationContext.xml file in src/main/resources (some kind of default in Maven based projects):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.blogspot.htnij" />

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value=""/>
        <property name="password" value=""/>
    </bean>

    <context:property-placeholder location="jdbc.properties"/>

</beans>

Nothing special here, we create dataSource based on class from org.apache.commons. Additionally, we tell Spring to scan our packages for annotations and put the configuration file as a property-placeholder. Jdbc.properties file looks like this:

jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:file:<your_path_to_db>
jdbc.username=
jdbc.password=

OK, configuration is ready, so now we can write some code. Let's start from POJO:

public class Actress {

    private Long id;
    private String name;
    private String lastName;
    private String breastSize;

    // Getters and setters here.
}

This class represents our table row in the world of objects. Now it's time for magic. Spring gives us special generic interface for OR mapping which we could use to write our own:

public class JdbcActressMapper implements RowMapper<Actress> {

    @Override
    public Actress mapRow(final ResultSet rs, final int rowNum) throws SQLException {
        final Actress actress = new Actress();
        actress.setId(rs.getLong("ID"));
        actress.setName(rs.getString("NAME"));
        actress.setLastName(rs.getString("LASTNAME"));
        actress.setBreastSize(rs.getString("BREAST_SIZE"));
        return actress;
    }
}

Our class has to implement just one method: mapRow(...). So far so good. Now let's see what we can do with created mapper in Spring. The class below is a simple DAO which implements JdbcDao<T> interface. Based on this class I'll try to show different ways to work with JDBC via Spring.

@Repository
public class JdbcDaoImpl implements JdbcDao<Actress> {

private transient NamedParameterJdbcTemplate template;

    @Autowired
    public void setDataSource(final DataSource dataSource) {
        this.template = new NamedParameterJdbcTemplate(new JdbcTemplate(dataSource));
    }

// some methods here. 

} 

We inject the data source object into our @Repository , which we declared in applicationContext.xml. Now we can do some magic:

1. Mapping to an object

 @Override
 public Integer getRowCount() {
        return template.getJdbcOperations().queryForObject("select count(id) from Actress", Integer.class);
    }

2. Mapping with custom mapper

    @Override
    public List<Actress> getAll() {
        return template.query("SELECT * FROM ACTRESS", new JdbcActressMapper());
    }

Here is the place where we can use created mapper.

3. Insert with list of arguments (or any other update type operations like update or delete)

    @Override
    public void insert(final Actress actress) {
        template.getJdbcOperations().update("INSERT INTO ACTRESS VALUES(?, ?, ?)", actress.getName(), actress.getLastName(),
                actress.getBreastSize());
    }

4. Update with named parameters and map
        
    @Override
    public void update(final Actress actress) {
        final Map<String Object> namedParameters = new HashMap<>();
        namedParameters.put("name", actress.getName());
        namedParameters.put("lastName", actress.getLastName());
        namedParameters.put("breastSize", actress.getBreastSize());
        namedParameters.put("id", actress.getId());
        template.update("UPDATE ACTRESS SET name = :name, lastname = :lastName, breast_size = :breastSize WHERE id = :id", namedParameters);
    }

5. Executing multiple operations
     
    @Override
    public int[] massUpdate(final List<Actress> list) {
        final List<Object[]> batch = new ArrayList<>();
        for (Actress actress : list) {
            Object[] values = new Object[]{
                actress.getName(),
                actress.getLastName(),
                actress.getBreastSize(),
                actress.getId()
            };
            batch.add(values);
        }
        return template.getJdbcOperations().batchUpdate("UPDATE ACTRESS SET name = ?, lastname = ?, breast_size = ? where id = ?", batch);
    }

In this solution SQL statement will not be compiled repeatedly and it will increase your system's performance.

6. Using named parameters and SQL parameter source

    @Override
    public List<Actress> getByBreast(final Actress actress) {
        final SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(actress);
        return template.query("SELECT * FROM Actress WHERE breast_size = :breastSize", namedParameters, new JdbcActressMapper());
    }

In this method named parameters were mapped from Actress.class, which means names of parameters in query should have the same names as fields in class.

I should mention the stored procedures here, but I'm planning to post about it in the future because it's a large topic. H2 DB doesn't support stored procedures in the relational way, as it should be (but it still supports Java methods as the procedures on the server side). 

I hope you enjoy this post and, as always, I'm waiting for your comments. You can also download this example from here. Remember to change jdbc.properties

0 komentarze:

Post a Comment