Spring JDBC抽象框架core包提供了JDBC模板类,其中JdbcTemplate是core包的核心类,主要提供以下五类方法:
jdbcTemplate.execute("create table user (uuid Integer, name varchar(50),age Integer)");
jdbcTemplate.execute("drop table user");
(1) jdbcTemplate.update("update user set age = 18 where uuid = 123456");
(2) jdbcTemplate.update("insert into user (name,age) values (?,?)",new Object[]{"sixmonth",18});
(3) jdbcTemplate.update("update user set age = ? where uuid = 123456",99);
//使用PreparedStatement防止sql注入
(4)jdbcTemplate.update("insert into user (name,age) values (?,?)",new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement pstmt) throws SQLException {
pstmt.setObject(1, "sixmonth");
pstmt.setObject(2, 18);
}});
1. 固定值
String sql="insert into user (name,age) values (?,?)";
List
2. 指定值
List userList = new ArrayList();
String sql = "insert into user(name,age) values(?,?)";
jdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, userList.get(i).getName());
ps.setString(2, userList.get(i).getAge());
}
@Override
public int getBatchSize() {
return userList.size();
}
});
1. 返回实体类集合:
String sql = "select name,age from user";
List userList=jdbcTemplate().query(sql,new BeanPropertyRowMapper(User.class));//无参数
//List userList=jdbcTemplate().query(sql,new Object[] { args1,args2 },new BeanPropertyRowMapper(User.class));//有参数
2. 返回自定义集合:
List userList = new ArrayList();
String sql = "select name,age from user where age = ?";
userList = jdbcTemplate.query(sql,new Object[] { args1,args2 }, new RowMapper()
{
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException
{
String s = "name is "rs.getString("name") + ", age is"+ rs.getInteger("age");
return s
}
});
1. queryForObject方法:
String sql="select * from user";
User user=jdbcTemplate.queryForObject(sql, new RowMapper(){
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user=new User();
user.setName(rs.getString("name"));
user.setAge(rs.getInteger("age"));
return user;
}
});
//String name = (String) jdbcTemplate.queryForObject( "select name from user where id = ?", new Object[] {4}, java.lang.String.class);
2. queryForList方法(多行数据):
String sql = "select name,age from user";
List
3. queryForMap方法(单行数据):
String sql = "select name,age from user where id = 4";
Map usermap = jdbcTemplate.queryForMap(sql);//无参
4.queryForLong/queryForInt方法:
Long lon = jdbcTemplate.queryForLong("SELECT COUNT(*) FROM user");
Int in = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM user");
spring自带的JdbcTemplate极大方便开发者进行数据持久层操作,本篇博客只是列举jdbcTemplate常用的一些方法,有兴趣可以继续深入研究!