ここでは、JdbcTemplateの `query()`メソッドを使用してデータベースからデータを照会または抽出する方法を示すいくつかの例を示します。

1.単一行のクエリ

ここでは、データベースから単一の行レコードをクエリまたは抽出し、それをモデルクラスに変換する2つの方法があります。

1.1カスタムRowMapper

一般的に、必要に応じてカスタムRowMapperを作成するために、RowMapperインターフェースを実装することが常に推奨されます。

package com.mkyong.customer.model;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

public class CustomerRowMapper implements RowMapper
{
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Customer customer = new Customer();
        customer.setCustId(rs.getInt("CUST__ID"));
        customer.setName(rs.getString("NAME"));
        customer.setAge(rs.getInt("AGE"));
        return customer;
    }

}

`queryForObject()`メソッドに渡すと、返された結果はカスタムの `mapRow()`メソッドを呼び出して値を適切に一致させます。

public Customer findByCustomerId(int custId){

    String sql = "SELECT **  FROM CUSTOMER WHERE CUST__ID = ?";

    Customer customer = (Customer)getJdbcTemplate().queryForObject(
            sql, new Object[]{ custId }, new CustomerRowMapper());

    return customer;
}

1.2 BeanPropertyRowMapper

Spring 2.5には、BeanPropertyRowMapperという便利なRowMapper実装が付属しています。この実装では、行の列の値を名前に一致させてプロパティにマップできます。プロパティと列の名前が同じであることを確認してください(例:プロパティ ‘custId’は列名 ‘CUSTID’または下線 ‘CUST__ID’と一致します)。

public Customer findByCustomerId2(int custId){

    String sql = "SELECT **  FROM CUSTOMER WHERE CUST__ID = ?";

    Customer customer = (Customer)getJdbcTemplate().queryForObject(
            sql, new Object[]{ custId },
            new BeanPropertyRowMapper(Customer.class));

    return customer;
}

2.複数の行のクエリ

今度は、データベースから複数の行を照会または抽出し、それをリストに変換します。

2.1手動でマップする

複数の戻り行では、 `queryForList()`メソッドでRowMapperがサポートされていないため、手動でマップする必要があります。

public List<Customer> findAll(){

    String sql = "SELECT **  FROM CUSTOMER";

    List<Customer> customers = new ArrayList<Customer>();

    List<Map> rows = getJdbcTemplate().queryForList(sql);
    for (Map row : rows) {
        Customer customer = new Customer();
        customer.setCustId((Long)(row.get("CUST__ID")));
        customer.setName((String)row.get("NAME"));
        customer.setAge((Integer)row.get("AGE"));
        customers.add(customer);
    }

    return customers;
}

2.2 BeanPropertyRowMapper

最も簡単な解決策はBeanPropertyRowMapperクラスを使用することです。

public List<Customer> findAll(){

    String sql = "SELECT **  FROM CUSTOMER";

    List<Customer> customers  = getJdbcTemplate().query(sql,
            new BeanPropertyRowMapper(Customer.class));

    return customers;
}

3.単一の値を照会する

この例では、データベースから単一の列の値を照会または抽出する方法を示します。

3.1単一の列名

これは、単一の列名をStringとして照会する方法を示しています。

public String findCustomerNameById(int custId){

    String sql = "SELECT NAME FROM CUSTOMER WHERE CUST__ID = ?";

    String name = (String)getJdbcTemplate().queryForObject(
            sql, new Object[]{ custId }, String.class);

    return name;

}

3.2行の総数

データベースから合計行数を照会する方法を示しています。

public int findTotalCustomer(){

    String sql = "SELECT COUNT(** ) FROM CUSTOMER";

    int total = getJdbcTemplate().queryForInt(sql);

    return total;
}

それを実行します

package com.mkyong.common;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;

public class JdbcTemplateApp
{
    public static void main( String[]args )
    {
         ApplicationContext context =
            new ClassPathXmlApplicationContext("Spring-Customer.xml");

         CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");

         Customer customerA = customerDAO.findByCustomerId(1);
         System.out.println("Customer A : " + customerA);

         Customer customerB = customerDAO.findByCustomerId2(1);
         System.out.println("Customer B : " + customerB);

         List<Customer> customerAs = customerDAO.findAll();
         for(Customer cust: customerAs){
             System.out.println("Customer As : " + customerAs);
         }

         List<Customer> customerBs = customerDAO.findAll2();
         for(Customer cust: customerBs){
             System.out.println("Customer Bs : " + customerBs);
         }

         String customerName = customerDAO.findCustomerNameById(1);
         System.out.println("Customer Name : " + customerName);

         int total = customerDAO.findTotalCustomer();
         System.out.println("Total : " + total);

    }
}

結論

JdbcTemplateクラスには、多くの便利なオーバーロードされたクエリメソッドが付属しています。

既に独自のカスタマイズクエリメソッドを作成する前に、既存のクエリメソッドを参照することをお勧めします。

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

ダウンロードする –

Spring-JdbcTemplate-Querying-Example.zip

(15 KB)