JdbcTemplate詳解2

來源:互聯網
上載者:User
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,提高了效率 轉自:http://tianya23.blog.51cto.com/1081650/375823 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.