JdbcTemplate详解 - 2

http://tianya23.blog.51cto.com/1081650/275292
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,提高了效率

转载于:https://blog.51cto.com/tianya23/375823

JdbcTemplate详解 - 2相关推荐

  1. spring29: JdbcTemplate详解

    spring提供用于操作jdbc工具类,类似DBUtils, 依赖连接池DataSource(数据源). 通过api import org.apache.commons.dbcp.BasicDataS ...

  2. spring教程--JdbcTemplate详解

    Spring的JdbcTemplate JdbcTemplate模板与DbUtils工具类比较类似. 1 Spring对持久层技术支持: JDBC:org.springframework.jdbc.c ...

  3. 详解jdbcTemplate和namedParameterJdbcTemplate

    我们开发DAO层时用的最多的就是ORM框架(Mybatis,hibernate)了.在有些特殊的情况下,ORM框架的搭建略显笨重,这时最好的选择就是Spring中的jdbcTemplate了.本文对j ...

  4. Spring JdbcTemplate方法详解

    2019独角兽企业重金招聘Python工程师标准>>> Spring JdbcTemplate方法详解 标签: springhsqldbjava存储数据库相关sql 2012-07- ...

  5. getinstance方法详解_二、设计模式总览及工厂模式详解

    二.架构师内功心法之设计模式 2.架构师内功心法之设计模式 2.1.课程目标 1.通过对本章内容的学习,了解设计模式的由来. 2.介绍设计模式能帮我们解决哪些问题. 3.剖析工厂模式的历史由来及应用场 ...

  6. Spring JDBC详解

    <Spring JDBC详解> 本文旨在讲述Spring JDBC模块的用法.Spring JDBC模块是Spring框架的基础模块之一. 一.概述 在Spring JDBC模块中,所有的 ...

  7. spring框架使用Quartz执行定时任务实例详解

    版权声明:本文为博主原创文章,如需转载,请标明出处. https://blog.csdn.net/alan_liuyue/article/details/80382324 Quartz简介 1.Qua ...

  8. Spring Boot 2.x基础教程:默认数据源Hikari的配置详解

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 作者 | 翟永超 来源 | http://blog.di ...

  9. Java编程配置思路详解

    Java编程配置思路详解 SpringBoot虽然提供了很多优秀的starter帮助我们快速开发,可实际生产环境的特殊性,我们依然需要对默认整合配置做自定义操作,提高程序的可控性,虽然你配的不一定比官 ...

最新文章

  1. 搞容器,必须考虑这五大安全要素
  2. Android Studio导入github项目详解
  3. ql的python学习之路-day10
  4. Windbg学习 (0x0001) 安装与基本配置
  5. Linux基础命令---apachectl
  6. 数据源管理 | PostgreSQL环境整合,JSON类型应用
  7. [系统审计]SAP HANA 中的系统审计策略管理
  8. docker 随笔记录
  9. js调用html页面跳转,js实现页面跳转的方法
  10. 产品经理常用的分析模型方法
  11. linux用ping命令测试网速,如何用ping 命令简单测试网速
  12. ASEMI肖特基二极管SBT40100VDC正向压降温度系数
  13. 使用 Ctrl + R 命令反向查找/搜索历史【笔记】
  14. pack与aligned的区别
  15. 500以内降噪蓝牙耳机推荐,2023年热门降噪蓝牙耳机推荐
  16. html 斜体变正体怎么变,WORD中编辑公式时怎样将斜体改成正体
  17. 本卦、互卦、变卦、错卦、综卦及作用
  18. ATF启动(六):bl32(OP-TEE)-->bl33 ATF ending
  19. java通过J2C获取用户名密码_WAS服务器上的J2C别名有什么用途?
  20. 反编译 jdk1.8 工具 [Procyon-Decompiler]

热门文章

  1. py文件 添加模块映射_Python模块的定义,模块的导入,__name__用法实例分析
  2. FPGA基础知识极简教程(8)详解三态缓冲器
  3. 读论文之《基于 FPGA 的并行全比较排序算法》
  4. 看看是否有人用USB偷插你的电脑
  5. 云栖大会的最后,阿里巴巴数据安全放了个大招!
  6. 信而泰推出100G多速率测试模块:填补中国通信产业链短板
  7. redis客户端jedis连接和spring结合
  8. 使用rel=noopener
  9. Win10如何查看我们的电池健康
  10. 数据库Sharding的基本思想和切分策略