package com.yiibai.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; } }
public Customer findByCustomerId(int custId){ String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?"; Customer customer = getSimpleJdbcTemplate().queryForObject( sql, new CustomerParameterizedRowMapper(), custId); return customer; }
public Customer findByCustomerId2(int custId){ String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?"; Customer customer = getSimpleJdbcTemplate().queryForObject(sql, ParameterizedBeanPropertyRowMapper.newInstance(Customer.class), custId); return customer; }
public List<Customer> findAll(){ String sql = "SELECT * FROM CUSTOMER"; List<Customer> customers = getSimpleJdbcTemplate().query(sql, ParameterizedBeanPropertyRowMapper.newInstance(Customer.class)); return customers; }
public String findCustomerNameById(int custId){ String sql = "SELECT NAME FROM CUSTOMER WHERE CUST_ID = ?"; String name = getSimpleJdbcTemplate().queryForObject( sql, String.class, custId); return name; }
public int findTotalCustomer(){ String sql = "SELECT COUNT(*) FROM CUSTOMER"; int total = getSimpleJdbcTemplate().queryForInt(sql); return total; }
執行它
package com.tw511.common; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiibai.customer.dao.CustomerDAO; import com.yiibai.customer.model.Customer; public class SimpleJdbcTemplateApp { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Customer.xml"); CustomerDAO customerSimpleDAO = (CustomerDAO) context.getBean("customerSimpleDAO"); Customer customerA = customerSimpleDAO.findByCustomerId(1); System.out.println("Customer A : " + customerA); Customer customerB = customerSimpleDAO.findByCustomerId2(1); System.out.println("Customer B : " + customerB); List<Customer> customerAs = customerSimpleDAO.findAll(); for(Customer cust: customerAs){ System.out.println("Customer As : " + customerAs); } List<Customer> customerBs = customerSimpleDAO.findAll2(); for(Customer cust: customerBs){ System.out.println("Customer Bs : " + customerBs); } String customerName = customerSimpleDAO.findCustomerNameById(1); System.out.println("Customer Name : " + customerName); int total = customerSimpleDAO.findTotalCustomer(); System.out.println("Total : " + total); } }