【Spring】官网教程阅读笔记(三):Spring中使用JDBC访问关系数据

来源:互联网 发布:哔哩哔哩没有mac版吗 编辑:程序博客网 时间:2024/05/01 18:59

【前言】REST教程第三篇,介绍Spring中使用JDBC访问数据的方法。原文链接 http://spring.io/guides/gs/relational-data-access/

【目标】在这里,你将使用JdbcTemplate创建一个应用来访问关系数据库中的数据

【准备工作】(由于轻车熟路了,我只列出pom.xml中dependencis中的内容,其他准备工作可以参考原文)

    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter</artifactId>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>        </dependency>        <dependency>            <groupId>com.h2database</groupId>            <artifactId>h2</artifactId>        </dependency>    </dependencies>


第一个是spring应用的artifact,第二个是jdbc,第三个是h2数据库


下面用到的一个简单的数据库访问逻辑:处理客户的姓名。这里创建一个Customer类

package hello;public class Customer {    private long id;    private String firstName, lastName;    public Customer(long id, String firstName, String lastName) {        this.id = id;        this.firstName = firstName;        this.lastName = lastName;    }    @Override    public String toString() {        return String.format(                "Customer[id=%d, firstName='%s', lastName='%s']",                id, firstName, lastName);    }    // getters & setters omitted for brevity}

存储和检索数据

Spring提供了一个模板类JdbcTemplate,能够很方便的用于SQL关系数据库和JDBC。大部分JDBC代码受限于被访问数据库的访问授权,连接管理,异常处理,错误校验,这些完全是(用户)代码不关心却不得不做的事情。JdbcTemplate模板帮你完成上面所以的操作!这样你只需要关注手头上的工作。

(下面的代码很长)

package hello;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;@SpringBootApplicationpublic class Application implements CommandLineRunner {    public static void main(String args[]) {        SpringApplication.run(Application.class, args);    }    @Autowired    JdbcTemplate jdbcTemplate;    @Override    public void run(String... strings) throws Exception {        System.out.println("Creating tables");        jdbcTemplate.execute("drop table customers if exists");        jdbcTemplate.execute("create table customers(" +                "id serial, first_name varchar(255), last_name varchar(255))");        String[] fullNames = new String[]{"John Woo", "Jeff Dean", "Josh Bloch", "Josh Long"};        for (String fullname : fullNames) {            String[] name = fullname.split(" ");            System.out.printf("Inserting customer record for %s %s\n", name[0], name[1]);            jdbcTemplate.update(                    "INSERT INTO customers(first_name,last_name) values(?,?)",                    name[0], name[1]);        }        System.out.println("Querying for customer records where first_name = 'Josh':");        List<Customer> results = jdbcTemplate.query(                "select id, first_name, last_name from customers where first_name = ?", new Object[] { "Josh" },                new RowMapper<Customer>() {                    @Override                    public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {                        return new Customer(rs.getLong("id"), rs.getString("first_name"),                                rs.getString("last_name"));                    }                });        for (Customer customer : results) {            System.out.println(customer);        }    }}

@SpringBootApplication注解在第一篇里讲过,是Spring4引入的一个注解,能完成多条注解的功能。

main()方法中的SpringApplication.run()在第一篇里也出现过,这里的作用和第一篇里相同。

SpringBoot执行H2数据库,一种内存数据库引擎,并且自动连接(代码中完全看不到指定了H2数据库。。。)。因为我们用了spring-jdbc,SpringBoot自动创建JdbcTemplate模板类。域@Autowired JdbcTemplate jdbcTemplate;会创建一个(JdbcTemplate)实例去自动加载并连接数据库,为我们提供Jdbc服务。

这个类实现了接口CommandLineRunner,该接口会在应用上下文加载完成后执行run()方法。

  • 首先,你需要用JdbcTemplate.execute()方法安装一些DDL;
  • 然后,用JdbcTemplate.update()向新生产的表中载人记录;
  • update() 方法的第一个参数是查询语句,最后一个参数(数组s)用以匹配查询语句中的占位符?。使用?占位符和变量绑定可以防止SQL注入攻击SQL injection attacks;
  • 最后,你使用query()方法在表中遍历符合条件的记录,这里也使用了占位符?和变量绑定。query()方法的最后一个参数是RowMapper<T>实例,他由你提供。Spring完成了90%的工作,但是他不知道你要怎样处理结果,所以你用这个实例把数据库查询到的结果(ResultSet中的数据)映射到Bean上,query()方法调用这个映射组装成以bean对象形式出现的结果集合

Build和运行

和前两篇相同,略去

【小结】掌握JdbcTemplate的用法,复习@SpringBootApplication注解和SpringApplication.run()方法,注解@AutoWired实现JdbcTemplate对象的实例化,CommandLineRunner接口,RowMapper<T>类在query中的用法

0 0