JdbcTemplate详解 - 2

1、由于之前JdbcTemplate的程序需要编写一堆的RowMapper的映射文件,显得有些臃肿,最好是根据pojo类和字段的名称进行自动的对应, 所以 SimpleJdbcTemplate支持使用Pojo中的属性进行自动赋值, 语法为':'开头。
public  class UserDaoSpringImpl  implements UserDao {
   private SimpleJdbcTemplate simpleJdbcTemplate =  new SimpleJdbcTemplate(
      JdbcUtils.getDataSource());

   public  void addUser(User user) {
    String sql =  "insert into user (name, money, birthday) values (:name, :money, :birthday)";
    SqlParameterSource param =  new BeanPropertySqlParameterSource(user);
    KeyHolder keyHolder =  new GeneratedKeyHolder();
     this.simpleJdbcTemplate.getNamedParameterJdbcOperations().update(sql,
        param, keyHolder);
    user.setId(keyHolder.getKey().intValue());
  }

   public  void delete(User user) {
    String sql =  "delete from user where id=?";
     this.simpleJdbcTemplate.update(sql, user.getId());
  }

   public User findUser(String loginName, String password) {
    String sql =  "select id, name, money, birthday    from user where name=?";
     return  this.simpleJdbcTemplate.queryForObject(sql,
        ParameterizedBeanPropertyRowMapper.newInstance(User. class),
        loginName);
  }

   public User getUser( int userId) {
    String sql =  "select id, name, money, birthday    from user where id=?";
     return  this.simpleJdbcTemplate.queryForObject(sql,
        ParameterizedBeanPropertyRowMapper.newInstance(User. class),
        userId);
  }

   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());

    sql =  "update user set name=:name, birthday=:birthday, money=:money where id=:id ";
     this.simpleJdbcTemplate.update(sql,  new BeanPropertySqlParameterSource(
        user));
  }

}
其中使用的 JdbcUtils获取数据源的代码如下:
public  final  class JdbcUtils {
   private  static String url =  "jdbc:mysql://localhost:3306/jdbc";
  private static String user = "root";
  private static String password = "";
  private static DataSource myDataSource = null;

  private JdbcUtils() {
  }

  static {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      // myDataSource = new MyDataSource2();
      Properties prop = new Properties();
      // prop.setProperty("driverClassName", "com.mysql.jdbc.Driver");
      // prop.setProperty("user", "user");

      InputStream is = JdbcUtils.class.getClassLoader()
          .getResourceAsStream("dbcpconfig.properties");
      prop.load(is);
      myDataSource = BasicDataSourceFactory.createDataSource(prop);
    } catch (Exception e) {
      throw new ExceptionInInitializerError(e);
    }
  }

  public static DataSource getDataSource() {
    return myDataSource;
  }

  public static Connection getConnection() throws SQLException {
    // return DriverManager.getConnection(url, user, password);
    return myDataSource.getConnection();
  }

  public static void free(ResultSet rs, Statement st, Connection conn) {
    try {
      if (rs != null)
        rs.close();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (st != null)
          st.close();
      } catch (SQLException e) {
        e.printStackTrace();
      } finally {
        if (conn != null)
          try {
            conn.close();
            // myDataSource.free(conn);
          } catch (Exception e) {
            e.printStackTrace();
          }
      }
    }
  }
}

2、 完成相同映射的类还包括:NamedParameterJdbcTemplate, 它将之前的占位符‘?’进行了取名,方便程序的阅读。 不过这样的SQL不能再数据库中直接执行,需要有Spring进行转换。

public  class NamedJdbcTemplate {
   static NamedParameterJdbcTemplate named =  new NamedParameterJdbcTemplate(
      JdbcUtils.getDataSource());

   /**
    * @param args
    */

   public  static  void main(String[] args) {
    User user =  new User();
    user.setMoney(10);
    user.setId(2);
    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);
     KeyHolder keyHolder =  new  GeneratedKeyHolder();
    named.update(sql, ps, keyHolder);
     int id = keyHolder.getKey().intValue();
    user.setId(id);
    
    Map map = keyHolder.getKeys();
  }

   static User findUser(User user) {
    String sql =  "select id, name, money, birthday    from user "
        +  "where money > :m and id < :id";
    Map params =  new HashMap();
     // params.put("n", user.getName());
    params.put( "m", user.getMoney());
    params.put( "id", user.getId());
    Object u = named.queryForObject(sql, params,  new BeanPropertyRowMapper(
        User. class));
     return (User) u;
  }

   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;
  }

}
【注意】
1、BeanPropertyRowMapper完成了对象到数据库字段的映射关系, 可以不再使用RowMapper来一一对应起来。如果RowMapper只使用1次,则可以直接使用内部类来完成,而不再需要专门的写一个类。
2、 KeyHolder, 其中保存了数据库中操作的主键,取得操作的主键后, 方便对进行操作的记录进行其他动作。
 
总之:利用反射技术,减少的了不必要的rowmapper,提高了效率
 

本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/375823,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值