| |
配制一个applicationcontext.xml如下
<? xml version = " 1.0 " encoding = " utf-8 " ?>
<! doctype beans public " -//spring//dtd bean//en " " http://www.springframework.org/dtd/spring-beans.dtd " >
< beans default - autowire = " autodetect " >
< import resource = " classpath:conf/spring/demo.xml " />
< bean id = " datasource " class = " org.apache.commons.dbcp.basicdatasource " >
< property name = " driverclassname " >
< value > com.mysql.jdbc.driver </ value >
</ property >
< property name = " url " >
< value > jdbc:mysql: // 192.168.1.10:3306/test?characterencoding=utf-8&charactersetresults=utf-8</value>
</ property >
< property name = " username " >
< value > root </ value >
</ property >
< property name = " password " >
< value > xx </ value >
</ property >
< property name = " maxactive " >
< value > 10 </ value >
</ property >
< property name = " maxidle " >
< value > 2 </ value >
</ property >
</ bean >
< bean id = " transactionmanager "
class = " org.springframework.jdbc.datasource.datasourcetransactionmanager " >
< property name = " datasource " >
< ref bean = " datasource " />
</ property >
</ bean >
< bean id = " jdbctemplate "
class = " org.springframework.jdbc.core.jdbctemplate " >
< property name = " datasource " >
< ref bean = " datasource " />
</ property >
</ bean >
</ beans >
对应的testdaoimpl中加入这部分代码
private jdbctemplate jdbctemplate;
 public jdbctemplate getjdbctemplate() {
return jdbctemplate;
}
public void setjdbctemplate(jdbctemplate jdbctemplate) {
this .jdbctemplate = jdbctemplate;
}
// 插入,修改和删除类似
string sql1 = " insert into testdb1 values('1','2') " ;
jdbctemplate.update(sql1);
// 查询
private class beanrowmapper implements rowmapper {
 public object maprow(resultset rs, int rownum) throws sqlexception {
string id = rs.getstring( " id " );
string title = rs.getstring( " title " );
bean bean = new bean(id,title);
return bean;
}
}
string sql1 = " select * from testdb1 " ;
list list = jdbctemplate.query(sql1, new beanrowmapper());
// call back (回调)
jt.execute( new connectioncallback() {
 public object doinconnection(java.sql.connection con) throws sqlexception, dataaccessexception {
return null ;
}
} );
|
|