SpringGuide系列:Accessing Relational Data using JDBC with Spring

26 篇文章 0 订阅

这个教程原来是用的内存数据库,在本文中我会先过一般原文的教程,后面会说一说怎么真正地连接Oracle11g,而不是用内存数据库。

Starting with Spring Initializr

在初始化应用程序中(https://start.spring.io/),引入依赖 JDBC API and H2 Database ,创建的Arctifact 取名:

relational-data-access

原文给出了POM.XML文件,本文略。

然后下载这个项目文件,relational-data-access.zip ,解压,然后在开发IDE环境SpringToolSuite4.exe 中 打开这个项目。

Create a Customer Object

在路径src/main/java/com/example/relationaldataaccess/Customer.java 创建这个java类。

package com.example.relationaldataaccess;

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
}

Store and Retrieve Data

Spring 提供了一个模板类JdbcTemplate,哪些重复的代码都在这个类中呢,你就用就这个类做你该做的可以了。在路径:src/main/java/com/example/relationaldataaccess/RelationalDataAccessApplication.java创建RelationalDataAccessApplication 类

package com.example.relationaldataaccess;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@SpringBootApplication
public class RelationalDataAccessApplication implements CommandLineRunner {

  private static final Logger log = LoggerFactory.getLogger(RelationalDataAccessApplication.class);

  public static void main(String args[]) {
    SpringApplication.run(RelationalDataAccessApplication.class, args);
  }

  @Autowired
  JdbcTemplate jdbcTemplate;

  @Override
  public void run(String... strings) throws Exception {

    log.info("Creating tables");

    jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
    jdbcTemplate.execute("CREATE TABLE customers(" +
        "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");

    // Split up the array of whole names into an array of first/last names
    List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
        .map(name -> name.split(" "))
        .collect(Collectors.toList());

    // Use a Java 8 stream to print out each tuple of the list
    splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

    // Uses JdbcTemplate's batchUpdate operation to bulk load data
    jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);

    log.info("Querying for customer records where first_name = 'Josh':");
    jdbcTemplate.query(
        "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
        (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
    ).forEach(customer -> log.info(customer.toString()));
  }
}

这段代码大概的作用如下:

创建日志对象log,这个以后会记录一些日志,不管它了。

jdbcTemplate.execute()会执行一个SQL语句,它首先是如果有customers表就把它给删除,然后创建表custoers,字段名分别为 序列号(Serial),名(firstname),姓(lastname),然后创建了

一个List,放入的是名字类似:"John Woo", "Jeff Dean", "Josh Bloch", "Josh Long",然后用批量更新命令做批量的插入。jdbcTemplate.batchUpdate(),反正就是给表加了几行呗。加完了数据就可以查询了

,用jdbcTemplate.query()。在日志中记录了下来。

 

然后就可以运行了, 在SpringToolSuite4.exe 中,右键点击项目:Run as Spring Boot App ,

如果成功了,IDE 的控制台会出现下图:

说明您成功了。

明天打算写一写如何连接真正的Oracle11g,数据库。这就是原创了,明天再写。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值