日期:2014-05-16  浏览次数:20403 次

Spring JdbcTemplate 简单示例

package com.xiva.jdbc.spring;

import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.xiva.jdbc.domain.Person;

public class JDBCTemplateSpring {
	
	static DataSource myDataSource;
	
	static DataSource getDataSource(){
		
		Properties prop = new Properties();
		try{
			InputStream is = JDBCTemplateSpring.class.getClassLoader().getResourceAsStream("dataSource.properties");
			prop.load(is);
			myDataSource = BasicDataSourceFactory.createDataSource(prop);
		}
		catch(Exception ioE){
			throw new ExceptionInInitializerError();
		}
		
		return myDataSource;
	}
	
	static Person findPerson(){
		Person person = new Person(); 
		JdbcTemplate jdbc = new JdbcTemplate(getDataSource());
		String sql = "select * from person where id=5";
		
		//这个方法只能获取rs size为1的对象;否则抛出异常IncorrectResultSizeDataAccessException
		person = jdbc.queryForObject(sql, new RowMapper<Person>(){

			@Override
			public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
				// TODO Auto-generated method stub
				Person person = new Person();
				person.setId(rs.getInt("id"));
				person.setName(rs.getString("name"));
				return person;
			}});
		
		return person;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Person person = findPerson();
		System.out.println(person);
	}
}

?

spring-transaction.jar------之前的spring版本中有一个叫spring-dao.jar的集成到这个包中

spring-jdbc.jar

以及其依赖的包