您的位置:首页 > 编程语言 > Java开发

spring jdbcTemplate

2015-09-20 09:14 344 查看
一.不使用xml配置文件的形式

(1)使用DriverManagerDataSource创建一个数据源

(2)创建一个jdbbcTemplate对象

(3)使用该对象执行sql语句

@Test
public void handle2(){
/**
*数据源
*/
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8");
dataSource.setUsername("root");
dataSource.setPassword("123456");

JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
String sql="create table tb_user(user_id int primary key,username varchar(60),password varchar(60))";
jdbcTemplate.execute(sql);
}


二.使用xml配置文件

(1)配置数据源

(2)配置jdbcTemplateBean

xml配置文件:

<!--  引入属性文件-->
<context:property-placeholder location="classpath:db.properties" file-encoding="utf-8"/>

<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
/>

<!-- 声明jdbcTemplateBean -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"
/>


(3)测试

@Test
public void handle3(){
String sql="insert into tb_user(user_id,username,password)values(1,'moweng','123456')";
jdbcTemplate.execute(sql);
}

三.jdbcTemplate的update

(1)int update

为不带占位符的sql语句提供便利

(2)int update(sql,Object[] object)

(3)int update(sql,Object[] object,int[] argTypes)

(4)int update(sql,PrepareStatementSetters pass)

(5)int update(preparedStatementCreators psc);

@Test
public void handl4(){
String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(sql,new Object[]{"23456","moweng"});
}
@Test
public void handl5(){
String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(sql,new Object[]{"234561","moweng"},new int[]{Types.VARBINARY,Types.VARBINARY});
}

@Test
public void handl6(){
String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(sql,new PreparedStatementSetter(){
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1,"23989");
ps.setString(2, "moweng");
}

});
}


@Test
public void handl7(){
final String sql="update tb_user set password=? where username=?";
jdbcTemplate.update(new PreparedStatementCreator() {

@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,"df9");
ps.setString(2, "moweng");
return ps;
}
});
}


四.spring提供了一个可以返回新增记录对应主键值的方法
int update(PreparedStatementCreator psc,KeyHolder generatedKeyHolder)

org.springwork.jdbc.support.KeyHolder是一个回调接口,spring使用它保存新增记录对应的主键。

Number getKey() throws InvalidDataAccessApiUsageException

当插入一行数据,主键不是复合键而是字符类型

Map<String,Object>getKeys()throws InvalidDataAccessApiUsageException

如果是复合键,则列和列值构成了Map中的一个Entry,如果是多个主键,则报错

List<Map<String,Object>>getKeys()throws InvalidDataAccessApiUsageException

如果返回了多个主键,即prepareStatement新增了多条记录,则每个主键对应一个Map,多个Map构成了一个list

@Test
public void handl8(){
final String sql="insert into tb_user(username,password)values(?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {

@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(2,"df90");
ps.setString(1, "yaping");
return ps;
}
},keyHolder);
System.out.println(keyHolder.getKey().intValue());
}

五.jdbcTemplate批量操作数据的方法
(1)public int[] batchUpdate(String[] sql)

多条sql语句组成一个数组(这些sql语句不带参数),该方法以批量方式执行这些sql语句spring在内部使用jdbc提供的批量更新API完成操作,如果底层不支持批量操作,spring将采用逐条更新的方式模拟批量更新

(2)public int[] batchUpdate(String sql,BatchPreparedStatementSetter ps)

对于同一结构带参sql语句多次进行数据更新操作,通过batchPreparedStatementSetter 回调接口进行批量参数绑定工作

int getBatchSize();指定本批次的大小

void setValues(preparestatement ps,int index)

@Test
public void handle9(){
String sql = "insert into tb_user(username,password)values(?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

@Override
public void setValues(PreparedStatement ps, int index) throws SQLException {
ps.setString(1,"moweng"+index);
ps.setString(2,"1234");
}

@Override
public int getBatchSize() {
return 5;
}
});
}

六.查询语句
RowcallbackHandler

@Test
public void handle11(){
String sql = "select * from tb_user where username=?";
jdbcTemplate.query(sql,new Object[]{"moweng"}, new RowCallbackHandler(){

@Override
public void processRow(ResultSet rs) throws SQLException {
System.out.println(rs.getString("username")+"=========="+rs.getString("password"));
}

});
}

七.调用存储过程
jdbcTemplate提供了两个调用存储过程的接口方法

(1)<T> execute(String callString,CallableStatementCallBack<T> action)

callstring 指定调用存储过程的sql语句;第二个参数CallableStatementCallback<T>是一个回调接口,该接口只有一个方法,

T doInCallableStatement(CallableStatement cs),用户可以在这个方法这进行输入参数绑定,输出参数注册以及返回数据的处理

(2)<T> execute(CallableStatementCreator csc,CallableStatementCallback<T> action)

CallableStatementCreator 负责创建callablestatement实例,绑定参数,注册输出参数,callableStatementcallback负责处理存储过程的返回结果

@Test
public void handle12(){
String sql="{call getCount(?,?)}";
Integer num = jdbcTemplate.execute(sql, new CallableStatementCallback() {

@Override
public Object doInCallableStatement(CallableStatement cs)
throws SQLException, DataAccessException {
cs.setInt(1, 1);
cs.registerOutParameter(2, Types.INTEGER);
cs.execute();
return cs.getInt(2);
}
});
System.out.println(num+"====");
}
@Test
public void handle13(){
String sql="{call getCount(?,?)}";
CallableStatementCreatorFactory fc = new CallableStatementCreatorFactory(sql);
fc.addParameter(new SqlParameter("in_userid",Types.INTEGER));
fc.addParameter(new SqlOutParameter("out_num",Types.INTEGER));
Map<String, Object> maps = new HashMap<String, Object>();
maps.put("in_userid", 1);
CallableStatementCreator cs = fc.newCallableStatementCreator(maps);
int num=jdbcTemplate.execute(cs,new CallableStatementCallback<Integer>() {

@Override
public Integer doInCallableStatement(CallableStatement css)
throws SQLException, DataAccessException {
css.execute();
return css.getInt(2);
}
});
System.out.println("==============="+num);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: