SpringJdbc

一、JdbcTemplate 

查询带有参数,和行映射方法:


public Object queryForObject(String sql, Object[] args, RowMapper rowMapper),使用自定义的UserRowMapper完成映射。

一个RowMapper的常用实现BeanPropertyRowMapper,该实现可将结果集转换成一个Java Bean(字段名与Java Bean属性名不符合规范,可用别名处理)。

public List query(String sql, Object[] args, RowMapper rowMapper)返回多个结果。

public int queryForInt(String sql)(如:select count(*) from user),其他结果比如String可用queryForObject方法向下转型。

public Map queryForMap(String sql, Object[] args)返回若类型的Map(key:字段名或别名,value:列值)。

public List queryForList(String sql, Object[] args)返回多Map。

 更新public int update(String sql, Object[] args)。

插入数据并获得结果:

public Object execute(ConnectionCallback action)

其他方法简介

 

public class JdbcTemplateTest {
  // JdbcTemplate是线程安全的
 static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource());
 public static void main(String[] args) {
  User user = findUser("zhangsan");
  // System.out.println("user:" + user);
  // System.out.println("users:" + findUsers(3));
  // System.out.println("user count:" + getUserCount());
  // System.out.println("user name:" + getUserName(1));
  System.out.println("data:" + getData(1));
 }
 static int addUser(final User user) {
  jdbc.execute(new ConnectionCallback() {
   public Object doInConnection(Connection con) throws SQLException,
     DataAccessException {
    String sql = "insert into user(name,birthday, money) values (?,?,?) ";
    PreparedStatement ps = con.prepareStatement(sql,
      Statement.RETURN_GENERATED_KEYS);
    ps.setString(1, user.getName());
    ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
    ps.setFloat(3, user.getMoney());
    ps.executeUpdate();
    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next())
     user.setId(rs.getInt(1));
    return null;
   }
  });
  return 0;
 }
 static Map getData(int id) {
  String sql = "select id as userId, name, money, birthday  from user where id="
    + id;
  return jdbc.queryForMap(sql);
 }
 static String getUserName(int id) {
  String sql = "select name from user where id=" + id;
  Object name = jdbc.queryForObject(sql, String.class);
  return (String) name;
 }
 static int getUserCount() {
  String sql = "select count(*) from user";
  return jdbc.queryForInt(sql);
 }
 static List findUsers(int id) {
  String sql = "select id, name, money, birthday  from user where id<?";
  Object[] args = new Object[] { id };
  int[] argTypes = new int[] { Types.INTEGER };
  List users = jdbc.query(sql, args, argTypes, new BeanPropertyRowMapper(
    User.class));
  return users;
 }
 static User findUser(String name) {
  String sql = "select id, name, money, birthday  from user where name=?";
  Object[] args = new Object[] { name };
   // BeanPropertyRowMapper行映射器,只要查询的字段名与类名一样就行(对于不同的可以使用别名 as xxx),对于不同命名规范它也会进行转化,如它自动将下划线法转化为骆峰法
  Object user = jdbc.queryForObject(sql, args, new BeanPropertyRowMapper(
    User.class));
  return (User) user;
 }
 static User findUser1(String name) {
  String sql = "select id, name, money, birthday  from user where name=?";
  Object[] args = new Object[] { name };
  Object user = jdbc.queryForObject(sql, args, new RowMapper() {
   public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    User user = new User();
    user.setId(rs.getInt("id"));
    user.setName(rs.getString("name"));
    user.setMoney(rs.getFloat("money"));
    user.setBirthday(rs.getDate("birthday"));
    return user;
   }
  });
  return (User) user;
 }
}

二、NamedParameterJdbcTemplate


lNamedParameterJdbcTemplate内部包含了一个JdbcTemplate,所以JdbcTemplate能做的事情NamedParameterJdbcTemplate都能干; NamedParameterJdbcTemplate相对于JdbcTemplate主要增加了参数可以命名的功能。

lpublic Object queryForObject(String sql, Map paramMap, RowMapper rowMapper)

lpublic Object queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper)

SqlParameterSource的两个主要实现MapSqlParameterSource

和BeanPropertySqlParameterSource

lpublic int update(String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder)保存数据获得主键。

 

public class NamedJdbcTemplate {
  // JdbcTemplate是线程安全的
 static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource());
 static NamedParameterJdbcTemplate named = new NamedParameterJdbcTemplate(
   JdbcUtils.getDataSource());
 public static void main(String[] args) {
  User user=new User();
  user.setMoney(10);
  user.setId(2);
//  System.out.println(findUser(user));
  System.out.println(findUser1(user));
 }
 static void addUser(User user){
  String sql = "insert into user(name,birthday, money) values (:name,:birthday,:money) ";//:后的命名要与列名一致
  SqlParameterSource ps=new BeanPropertySqlParameterSource(user);//从user中取出数据,与sql语句中一一对应将数据换进去
  KeyHolder keyHolder=new GeneratedKeyHolder();
  named.update(sql, ps, keyHolder);
  int id=keyHolder.getKey().intValue();//获得主键
  user.setId(id);
  Map map=keyHolder.getKeys();
 }
 static User findUser1(User user) {
  String sql = "select id, name, money, birthday  from user where money>:money and id<:id";
  SqlParameterSource ps=new BeanPropertySqlParameterSource(user);
  Object u=named.queryForObject(sql, ps, new BeanPropertyRowMapper(User.class));
  return (User) u;
 }
 static User findUser(User user) {
  String sql = "select id, name, money, birthday  from user where money>:m and id<:id";
  Object[] args = new Object[] {user.getName(),user.getMoney(),user.getId() };
  Map params=new HashMap();
  params.put("m", user.getMoney());
  params.put("id", user.getId());
  Object u=named.queryForObject(sql, params, new BeanPropertyRowMapper(User.class));
  return (User) u;
 }

  三、 SimpleJdbcTemplate


SimpleJdbcTemplate内部包含了一个NamedParameterJdbcTemplate;所以NamedParameterJdbcTemplate能做的事情SimpleJdbcTemplate都能干,SimpleJdbcTemplate相对于NamedParameterJdbcTemplate主要增加了JDK5.0的泛型和可变长度参数支持。

public <T> List<T> query(String sql, ParameterizedRowMapper<T> rm, Object... args)

public <T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, SqlParameterSource args)

public <T> List<T> query(String sql, ParameterizedRowMapper<T> rm, SqlParameterSource args)

getJdbcOperations返回的是JdbcOperations(实现JdbcTemplate)

getNamedParameterJdbcOperations返回的是NamedParameterJdbcOperations(实现是NamedParameterJdbcTemplate)

 

public class UserDaoSpringImpl implements UserDao {
 private SimpleJdbcTemplate simpleJdbcTemplate=new SimpleJdbcTemplate(JdbcUtils.getDataSource());
 @Override
 public void addUser(User user) {
  String sql="insert into user (name,money,birthday) value (:name,:money,:birthday)";
  SqlParameterSource param=new BeanPropertySqlParameterSource(user);
  KeyHolder keyHolder=new GeneratedKeyHolder();
  this.simpleJdbcTemplate.getNamedParameterJdbcOperations().update(sql, param, keyHolder);
  user.setId(keyHolder.getKey().intValue());
 }
 @Override
 public User getUser(int userId) {
  String sql="selec id,name,money,birthday from where id=?";
  return this.simpleJdbcTemplate.queryForObject(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class), userId);
 }
 @Override
 public User findUser(String name, String password) {
  String sql="selec id,name,money,birthday from where name=?";
  return this.simpleJdbcTemplate.queryForObject(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class), name);
 }
 @Override
 public void update(User user) {
//  String sql="update user set name=?,birthday=?,money=? where id=?";
//  this.simpleJdbcTemplate.update(sql, user.getName(),user.getBirthday(),user.getMoney(),user.getId());
  String sql="update user set name=:name,birthday=:birthday,money=:money where id=:id";
  this.simpleJdbcTemplate.update(sql,new BeanPropertySqlParameterSource(user));
 }
 @Override
 public void delete(User user) {
  String sql="delete from user where id="+user.getId();
  this.simpleJdbcTemplate.update(sql, user.getId());
 }
}

 

 

你可能感兴趣的:(SpringJdbc)