SpringBoot官网例子(4)——Accessing Relational Data using JDBC with Spring(使用JDBC访问关系数据)

1、准备工作

原文:https://spring.io/guides/gs/relational-data-access/

  • >=1.8的JDK
  • Eclipse(其它任何合适的IDE)
  • Maven3.2(官网也有Gradle的构建

2、 POM文件

仍然是一个子模块,父工程的pom https://blog.csdn.net/csdn86868686888/article/details/103758256


  4.0.0
  
    com.springboot
    springboot-parent
    0.0.1-SNAPSHOT
  
  springboot-JDBC
  
  
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-data-jdbc
		

		
			com.h2database
			h2
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
			
				
					org.junit.vintage
					junit-vintage-engine
				
			
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	
  

3、工程

工程结构:

SpringBoot官网例子(4)——Accessing Relational Data using JDBC with Spring(使用JDBC访问关系数据)_第1张图片

代码:

package com.springboot.entity;

public class Customer {
	  private long id;
	  private String firstName, lastName;

	//省略get,set方法

	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);
	  }
}
package com.springboot;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

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.core.io.buffer.LimitedDataBufferList;
import org.springframework.jdbc.core.JdbcTemplate;

import com.springboot.entity.Customer;

@SpringBootApplication
public class Application implements CommandLineRunner{

	private static final Logger log=LoggerFactory.getLogger(Application.class);
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
	@Override
	public void run(String... args) 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))");
	    
	    List splitUpNames=Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long")
								    	  .stream()
								    	  .map(name->name.split(" "))
								    	  .collect(Collectors.toList());
	    
	    splitUpNames.forEach(name->log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));
	    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())); 
	}
	
}

4、总结

执行结果是这样的:

 主要功能是利用Spring提供的JDBC访问关系型数据库,这里为了演示方便使用的是嵌入内存的关系型数据库h2,插入、查询时候使用了java8以后提供的函数式接口以及Lambda表达式。

代码戳https://github.co/github20131983/springboot

你可能感兴趣的:(SpringBoot)