1. 程式人生 > >12 Spring框架的JDBC模板的簡單操作

12 Spring框架的JDBC模板的簡單操作

  •  Spring框架的JDBC模板的簡單操作

此例繼續使用上一節建立的環境來做測試

package demo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.activation.DataSource;
import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import domain.Account;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value="classpath:applicationContext.xml")
public class Demo1 {
	
		
	/**
	 * Spring框架的JDBC模板的簡單操作
	 * 因與修改的數字都是double所有在數字後面都加上小寫字母d
	 */
	@Test
	// 插入操作
	public void run1() {
		template.update("insert into t_account values (null,?,?)", "test1", 50000);
	}
	@Test
	// 修改操作
	public void run2(){
		template.update("update t_account set name=?,money =? where id = ?", "test1",10000d,5);
	}
	@Test
	// 刪除操作
	public void run3(){
		template.update("delete from t_account where id = ?", 5);
	}
	
	/**
	 * 模板查詢操作
	 * 需要實現RowMapper<?>介面,可重用。
	 */
	@Test
	// 查詢一條記錄
	public void run4(){
		Account account = template.queryForObject("select * from t_account where id = ?", new BeanMapper(), 1);
		System.out.println(account);
	}
	
	@Test
	// 查詢所有記錄
	public void demo5(){
		List<Account> list = template.query("select * from t_account", new BeanMapper());
		for (Account account : list) {
			System.out.println(account);
		}
	}
	
}

/**
 * 1.實現RowMapper介面的mapRow(ResultSet rs, int arg1)方法
 * 2.例項化需要的bean類
 * 3.手動賦值各個成員變數
 * 4.最後返回該例項
 * @author Administrator
 *
 */
class BeanMapper implements RowMapper<Account>{
	
	@Override
	public Account mapRow(ResultSet rs, int arg1) throws SQLException {
		Account account = new Account();
		account.setId(rs.getInt("id"));
		account.setName(rs.getString("name"));
		account.setMoney(rs.getDouble("money"));
		return account;
	}

}