spring jdbcTemplate测试

1、DAO interface
package test.dao;

import java.util.List;

import test.model.Book;

public interface BookDAO {
void create(Book book);
List<Book> queryByAuthor(String author);
}

2、DAO Impl

package test.dao.impl;

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

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import test.dao.BookDAO;
import test.model.Book;

public class BookDAOImpl extends JdbcDaoSupport implements BookDAO {

class BookRowMapper implements RowMapper {

public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Book book = new Book();
book.setId(rs.getLong("id"));
book.setName(rs.getString(
"name"));
book.setAuthor(rs.getString(
"author"));
return book;
}

}

public void create(Book book) {
getJdbcTemplate().update(
"insert into book(id,name,author)values(book_seq.nextval,?,?)",
new Object[] { book.getName(), book.getAuthor() });
}

public List<Book> queryByAuthor(String author) {
return getJdbcTemplate().query(
"select * from book where author=?", new Object[]{author}, new BookRowMapper());
}


}
3、spring context
<?xml version=
"1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

    <!--========WebDb DataSource========================================================================-->
<!-- -->
<bean id=
"webdbDataSource"
          class=
"org.apache.commons.dbcp.BasicDataSource"
          destroy-method=
"close">
        <property name=
"driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name=
"url" value="jdbc:oracle:thin:@localhost:1521:lunzi"/>
        <property name=
"username" value="webnews"/>
        <property name=
"password" value="123456"/>
    </bean>
    
<bean id=
"jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name=
"dataSource" ref="webdbDataSource"/>
</bean>

<bean id=
"bookDao" class="test.dao.impl.BookDAOImpl">
<property name=
"dataSource" ref="webdbDataSource"/>
</bean>

</beans>
4、测试类
package test.dao.test;

import java.util.List;

import test.dao.BookDAO;
import test.model.Book;

public class BookDAOTest extends BaseDaoTestCase {
public BookDAO bookDao;

public void setBookDao(BookDAO bookDao){
this.bookDao = bookDao;
}

/*public void testCreateBook(){
Book book = new Book();
book.setAuthor("lunzi2");
book.setName("cow2");
this.bookDao.create(book);
}*/


public void testQueryByAuthor(){
List<Book> list = this.bookDao.queryByAuthor(
"lunzi2");

for(Book book:list){
System.out.println(book.getName());
}
super.assertNotNull(list);
}
}
lunzi   2008-02-17 15:32:56 评论:1   阅读:3337   引用:0
@2008-04-14 11:23:32  游客
谢谢了,刚好需要了解JdbcTemplate

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2004-2010 powered by YuLog