開発者ドキュメント

Spring JdbcTemplate JdbcDaoSupportの例

Spring JDBC開発では、

JdbcTemplate`クラスと

JdbcDaoSupport`クラスを使用して、データベース操作プロセス全体を簡素化できます。

このチュートリアルでは、前の(No JdbcTemplateのサポート)と後の(JdbcTemplateをサポートする)サンプルの違いを見るために、最後のリンク//spring/maven-spring-jdbc-example/[Spring JDBCの例]を再利用します。

1. JdbcTemplateを使用しない例

Witout JdbcTemplateでは、すべてのDAOデータベース操作メソッド(挿入、更新、削除)で多くの冗長コード(接続の作成、接続の切断、例外の処理)を作成する必要があります。それは効率的ではなく、醜い、間違いやすい、面倒ではありません。

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void insert(Customer customer){

        String sql = "INSERT INTO CUSTOMER " +
                "(CUST__ID, NAME, AGE) VALUES (?, ?, ?)";
        Connection conn = null;

        try {
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, customer.getCustId());
            ps.setString(2, customer.getName());
            ps.setInt(3, customer.getAge());
            ps.executeUpdate();
            ps.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);

        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {}
            }
        }
    }

2. JdbcTemplateを使用した例

JdbcTemplateを使用すると、JdbcTemplateが自動的にそれを処理するため、冗長コードに多くの型を保存することができます。

    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void insert(Customer customer){

        String sql = "INSERT INTO CUSTOMER " +
            "(CUST__ID, NAME, AGE) VALUES (?, ?, ?)";

        jdbcTemplate = new JdbcTemplate(dataSource);

        jdbcTemplate.update(sql, new Object[]{ customer.getCustId(),
            customer.getName(),customer.getAge()
        });

    }

異なって見なさいか。

3. JdbcDaoSupportの例

JdbcDaoSupportを拡張すると、データソースを設定し、クラス内のJdbcTemplateはもはや必要なくなり、JdbcCustomerDAOに正しいデータソースを注入するだけで済みます。また、getJdbcTemplate()メソッドを使用してJdbcTemplateを取得できます。

    public class JdbcCustomerDAO extends JdbcDaoSupport implements CustomerDAO
    {
      //no need to set datasource here
       public void insert(Customer customer){

        String sql = "INSERT INTO CUSTOMER " +
            "(CUST__ID, NAME, AGE) VALUES (?, ?, ?)";

        getJdbcTemplate().update(sql, new Object[]{ customer.getCustId(),
                customer.getName(),customer.getAge()
        });

    }
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mkyongjava"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
    </bean>

</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

ソースコードをダウンロードする

ダウンロードする –

Spring-JDBC-Example.zip

(15 KB)

モバイルバージョンを終了