Spring+jdbc的例子

测试
package tarena.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import tarena.dao.BookDao;
import tarena.domain.Book;

public class BookDaoTest {

	public static void main(String[] args) {
		ApplicationContext txt = new ClassPathXmlApplicationContext("applicationContext.xml");
		BookDao dao = (BookDao) txt.getBean("bookDao");
		
		Book book = new Book("hibernate core",560);
		//book.setId(1);
		dao.save(book);
               //测试id是否生成并返回
		System.out.println(book.getId());
	//	dao.update(book);
	
		//System.out.println(	dao.findById(1).getName());
	//	dao.delete(3);
		List list = dao.findByPrice(10, 3000);
		for (Object object : list) {
			Book b = (Book)object;
			System.out.println(b.getId()+":"+b.getName()+":"+b.getPrice());
		}
	}
}

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0.xsd">

	<!--配置数据源-->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<value>
				jdbc:mysql://localhost:3306/openlab?useUnicode=true&amp;characterEncoding=utf8
			</value>
		</property>
		<property name="username" value="openlab" />
		<property name="password" value="open123" />
	</bean>
	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<bean id="bookDao" class="tarena.dao.jdbc.BookDaoImpl">
		<constructor-arg ref="jdbcTemplate"></constructor-arg>
	</bean>
	
	</beans>

BookDao接口
package tarena.dao;

import java.util.List;
import tarena.domain.Book;
public interface BookDao {
	void save(Book book);
	void update(Book book);
	void delete(int id);
	Book findById(int id);
	List findByPrice(double from, double to);
}

Spring提供的jdbcTemplate实现
package tarena.dao.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import tarena.dao.BookDao;
import tarena.domain.Book;

public class BookDaoImpl implements BookDao {

	private JdbcTemplate jt;

	public BookDaoImpl() {
		super();
	}

	public BookDaoImpl(JdbcTemplate jt) {
		super();
		this.jt = jt;
	}

	public void delete(int id) {
		String sql = "delete from book where id=?";
		jt.update(sql, new Object[] { id });
	}

	public Book findById(final int id) {
		String sql = "select * from book where id=?";
		return (Book) jt.query(sql, new Object[] { id },
				new ResultSetExtractor() {
					public Object extractData(ResultSet rs)
							throws SQLException, DataAccessException {
						//查询返回的rs要自己来处理,因为查询的条件不同,返回结果集也不同
						if (rs.next()) {
							String name = rs.getString("name");
							double price = rs.getDouble("price");
							return new Book(id, name, price);
						}
						return null;
					}
				});
	}

	public List findByPrice(double from, double to) {
		String sql = "select * from book where price between ? and ?";
		return jt.query(sql, new Object[] { from, to }, new RowMapper() {
			//自动将每条记录封装到集合中去
			public Object mapRow(ResultSet rs, int arg1) throws SQLException {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				double price = rs.getDouble("price");
				return new Book(id, name, price);
			}
		});
	}

	public void save(final Book book) {
		final String sql = "insert into book(name,price) values(?,?)";
		//jdbc要由自己来预编译创建定义preparedStatement因为这其中,是要取得数据库自动生成的id
		PreparedStatementCreator psc = new PreparedStatementCreator(){
			public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
				PreparedStatement ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
				ps.setString(1, book.getName());
				ps.setDouble(2, book.getPrice());
				return ps;
			}
		};
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jt.update(psc, keyHolder);
		//通过keyHolder来获取id序列
		long idkey = (Long) keyHolder.getKey();
		book.setId((int)idkey);
	}

	public void update(Book book) {
		String sql = "update book set name=?,price=? where id=?";
		jt.update(sql, new Object[] { book.getName(), book.getPrice(),
				book.getId() });
	}

}


pojo类
package tarena.domain;

public class Book {

	private int id;
	private String name;
	private double price;
	
	
	public Book() {
		super();
	}
	public Book(String name, double price) {
		super();
		this.name = name;
		this.price = price;
	}
	public Book(int id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

你可能感兴趣的:(java,DAO,spring,sql,jdbc)