webservice,spring boot demo(spring jdbc訪問數據)

 2023-11-19 阅读 36 评论 0

摘要:Accessing Relational Data using JDBC with Spring 您將使用Spring JdbcTemplate?構建應用,訪問數據庫中數據。 下面的簡單數據訪問邏輯,將與下面的管理客戶的姓氏和名字。 表示該數據在應用程序級別,創建一個客戶?類。 public class Customer {private long i

Accessing Relational Data using JDBC with Spring


您將使用Spring JdbcTemplate?構建應用,訪問數據庫中數據

下面的簡單數據訪問邏輯,將與下面的管理客戶的姓氏和名字。 表示該數據在應用程序級別,創建一個客戶?類。

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;}@Overridepublic String toString() {return String.format("Customer[id=%d, firstName='%s', lastName='%s']",id, firstName, lastName);}// getters & setters omitted for brevity
}
Spring提供了模板類?JdbcTemplate?這使得它很容易使用關系數據庫SQL和JDBC。webservice、 大部分的JDBC代碼、配置、異常處理和通用錯誤檢,可以用JdbcTemplate 很好實現,你所要做的就是專注于手頭的任務。

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 Application implements CommandLineRunner {private static final Logger log = LoggerFactory.getLogger(Application.class);public static void main(String args[]) {SpringApplication.run(Application.class, args);}@AutowiredJdbcTemplate jdbcTemplate;@Overridepublic 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 namesList<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 listsplitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));// Uses JdbcTemplate's batchUpdate operation to bulk load datajdbcTemplate.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()));}
}
@SpringBootApplication包括?@Configuration?@EnableAutoConfiguration?@ComponentScan

SpringApplication.run()用來啟動容器應用

spring boot?spots?H2?,一個內存中的關系數據庫引擎,并自動創建一個連接。 因為我們使用的是?spring jdbc,
spring的自動創建一個JdbcTemplate?。 用?@ autowired JdbcTemplate 注解自動加載它,使其可用。springboot。

這Application?類實現spring boot中的?CommandLineRunner?,這意味著它將執行?run()?方法在應用程序加載啟動的時候。

對于單一的insert語句,?JdbcTemplate的插入?方法是好的。 但對于多個插入,最好使用batchUpdate?

使用???對于參數避免?SQL注入攻擊?指示JDBC綁定變量。spring jpa。

使用maven構建項目,下面是maven
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.springframework</groupId><artifactId>gs-relational-data-access</artifactId><version>0.1.0</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.2.5.RELEASE</version></parent><properties><java.version>1.8</java.version></properties><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><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
The?Spring Boot Maven plugin?提供很多方便的特性

  • 它集成的所有jar文件的類路徑中,構建一個單一的、可運行的“uber-jar”,這使得它更方便執行和提供服務。

    它搜索 public staticvoid main()?標志作為一個可運行的類方法。

    它提供了一個內置的依賴項解析器,設置版本號相匹配 spring boot依賴性,你可以重寫。












版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/183419.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息