• 第10章 通过Spring和JDBC征服数据库


     1、配置数据源

    无论选择 Spring 的哪种数据访问方式,你都需要配置一个数据源的引用。 Spring 提供了在 Spring 上下文中配置数据源 bean 的多种方式,包括:

    • 通过 JDBC 驱动程序定义的数据源;
    • 通过 JNDI 查找的数据源;
    • 连接池的数据源。

     这里使用阿里的druid,github地址https://github.com/alibaba/druid,具体配置可以参考github的wiki

      @Bean
        public DataSource dataSource(){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(env.getProperty("jdbc.url"));
            dataSource.setUsername(env.getProperty("jdbc.username"));
            dataSource.setPassword(env.getProperty("jdbc.password"));
            return dataSource;
        }

    2、在spring中使用jdbc

    Spring 将数据访问的样板代码抽象到模板类之中。 Spring 为 JDBC 提供了三个模板类供选择:

    • JdbcTemplate :最基本的 Spring JDBC 模板,这个模板支持简单的 JDBC 数据库访问功能以及基于索引参数的查询;
    • NamedParameterJdbcTemplate :使用该模板类执行查询时可以将值以命名参数的形式绑定到 SQL 中,而不是使用简单的索引参
    • 数;
    • SimpleJdbcTemplate :该模板类利用 Java 5 的一些特性如自动装箱、泛型以及可变参数列表来简化 JDBC 模板的使用。

    以前,在选择哪一个 JDBC 模板的时候,我们需要仔细权衡。但是从 Spring 3.1 开始,做这个决定变得容易多了。 SimpleJdbcTemplate 已
    经被废弃了,其 Java 5 的特性被转移到了 JdbcTemplate 中,并且只有在你需要使用命名参数的时候,才需要使
    用 NamedParameterJdbcTemplate 。这样的话,对于大多数的 JDBC 任务来说, JdbcTemplate 就是最好的可选方案,这也是本小节中
    所关注的方案。

    配置jdbc模板

        @Bean
        public JdbcTemplate jdbcTemplate(){
            return new JdbcTemplate(dataSource());
        }

    数据库读写

    @Repository
    public class IStudentImpl implements IStudent {
        private JdbcOperations jdbcOperations;
    
        @Autowired
        public IStudentImpl(JdbcOperations jdbcOperations){
            this.jdbcOperations = jdbcOperations;
        }
    
        public Student getStudentById(String id) {
            return jdbcOperations.queryForObject("select * from student where id = ?",new StudentRowMapper(),id);
        }
        private static final class StudentRowMapper implements RowMapper<Student>{
    
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student = new Student();
                student.setId(resultSet.getString("id"));
                student.setSex(resultSet.getString("sex"));
                student.setName(resultSet.getString("name"));
                student.setAge(resultSet.getInt("age"));
                return student;
            }
        }
    }
  • 相关阅读:
    深入了解ibatis源码----简单ibatis示例代码
    struts深入理解之登录示例的源码跟踪
    struts深入原理之RequestProcessor与xml
    struts学习
    Debugging WebLogic Server Applications Using Eclipse and the WebLogic-Plugin
    论做人与做事
    网络编程I/O功能介绍
    Python标准库:内置函数format(value[, format_spec])
    swift 笔记 (七) —— 关闭
    在自由软件的价值
  • 原文地址:https://www.cnblogs.com/xuzhen97/p/9329450.html
Copyright © 2020-2023  润新知