Maven搭建Spring Boot JDBC

编写pom.xml添加依赖

完整项目Github地址:https://github.com/RottenCuke/SpringBootJDBC

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>comgroupId>
  <artifactId>Spring-Boot-JDBCartifactId>
  <packaging>warpackaging>
  <version>1.0-SNAPSHOTversion>
  <name>Spring-Boot-JDBC Maven Webappname>
  <url>http://maven.apache.orgurl>

  <parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>1.5.3.RELEASEversion>
  parent>

  <properties>
    <java.version>1.8java.version>
  properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-jdbcartifactId>
    dependency>
    <dependency>
      <groupId>com.h2databasegroupId>
      <artifactId>h2artifactId>
    dependency>
  dependencies>


  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-maven-pluginartifactId>
      plugin>
    plugins>
  build>


project>

编写实体类

package hello;

/**
 * Created by abb on 17-5-17.
 */
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 "Customer{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

Application类

注:
1.  jdbcTemplate将数据保存在内存当中

package hello;

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.Collection;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Created by abb on 17-5-17.
 */
@SpringBootApplication
public class Application implements CommandLineRunner{

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

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

    @Autowired
    JdbcTemplate jdbcTemplate;

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

        logger.info("Create tables");

        jdbcTemplate.execute("drop table customers if EXISTS ");
        jdbcTemplate.execute("CREATE TABLE customers(" +
                "id SERIAL, first_name VARCHAR, last_name VARCHAR )");

        // 将整个姓名分割为first_name 和 last_name

        /*         stream/元素流,是java8中的新特性                   */
        /*         map映射每个元素到相应的结果,这里是分割每个字符串      */
        /*         Collectors实现归约操作,将流转换为集合              */

        List splitUpNames = Arrays.asList("John Woo", "Lenz Liu", "Josn Long").stream()
                .map(name -> name.split(" "))
                .collect(Collectors.toList());

        // 使用java8 stream输出list每个元组
        splitUpNames.forEach(name -> logger.info(String.format("Inserting customer record for %s %s",name[0],name[1])));

        // 使用jdbcTemplate的批次操作处理数据
        jdbcTemplate.batchUpdate("INSERT INTO customers(first_name,last_name) VALUES (?,?)",splitUpNames);

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

你可能感兴趣的:(Spring)