5. Spring uses JDBC to access relational data

Source: Internet
Author: User
Tags connection pooling sql injection java 8 stream

This guide walks you through the process of using spring to access relational data. Read the original

1. What will you build?

You will use spring's jdbctemplate to build an application to access the data stored in the relational database.

2. What do you need to prepare?
    • About 15 minutes

    • A favorite text editor or IDE

    • JDK 1.8 or higher

    • Gradle 4+ or Maven 3.2+

    • You can also import code into your IDE

      • Spring Tool Suite (STS)

      • IntelliJ idea

3. How do I implement this guide?

We still use STS to import code in this way.

1. Open sts,new ———— > Import sprnig geting Started Content

2. Enter RelA, search to find relational Data Access

3. Create a Customer object

You will use the simple data access logic below to manage the customer's first and last name. To represent this data at the application level, create a customer class.

Src/main/java/hello/customer.java

 PackageHello; Public classCustomer {Private LongID; PrivateString FirstName, LastName;  PublicCustomer (LongID, String firstName, String lastName) {         This. ID =ID;  This. FirstName =FirstName;  This. LastName =LastName; }     PublicCustomer () {} Public LonggetId () {returnID; }     Public voidSetId (LongID) { This. ID =ID; }     PublicString Getfirstname () {returnFirstName; }     Public voidsetfirstname (String firstName) { This. FirstName =FirstName; }     PublicString Getlastname () {returnLastName; }     Public voidsetlastname (String lastName) { This. LastName =LastName; } @Override PublicString toString () {returnString.Format ("customer[id=%d, firstname= '%s ', lastname= '%s ']", ID, firstName, lastName); }}

4. Storing and retrieving data

Spring provides a template class named JdbcTemplate that makes it easy to work with SQL relational databases and JDBC. Most JDBC code is trapped in resource acquisition, connection management, exception handling, and general error checking, which is completely unrelated to the intent of the code. JdbcTemplate handles all of these issues for you. All you have to do is focus on the task at hand.

Src/main/java/hello/application.java

 PackageHello;Importjava.util.Arrays;Importjava.util.List;Importjava.util.stream.Collectors;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.boot.CommandLineRunner;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.jdbc.core.JdbcTemplate; @SpringBootApplication Public classApplicationImplementsCommandlinerunner {Private Static FinalLogger log = Loggerfactory.getlogger (application.class);  Public Static voidMain (String args[]) {springapplication.run (application.class, args);    } @Autowired jdbctemplate JdbcTemplate; @Override Public voidRun (String ... strings)throwsException {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 to an array of first/last nameslist<object[]> splitupnames = arrays.aslist ("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long"). Stream (). Map (nameName.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", 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 =?",NewObject[] {"Josh"}, (RS, RowNum)-NewCustomer (Rs.getlong ("id"), rs.getstring ("first_name"), Rs.getstring ("Last_Name")) . ForEach (Customer-Log.info (customer.tostring ())); }}
@SpringBootApplication is a handy comment that adds all of the following:
    • @Configuration to mark the class as the source of the bean definition for the application context.
    • @EnableAutoConfiguration notifies spring boot to start adding beans based on the classpath setting, and other beans and various property settings.
    • @ComponentScan tell spring to look for additional components, configurations, and services in the Hello package. In this case, there is no.

The main () method launches the application using the Spring Boot Springapplication.run () method. Have you noticed that there is not a single line of XML? No web. xml file. This Web application is 100% pure Java, and you do not have to deal with configuring any pipelines or infrastructure.

Spring Boot supports H2, an in-memory relational database engine, and automatically creates a connection. Because we are using spring-jdbc,spring boot will automatically create a jdbctemplate. @Autowired the JdbcTemplate field automatically loads it and makes it available.

This application class implements the spring boot Commandlinerunner, which means that it executes the run () method after the application context is loaded.

First, you use the JdbcTemplate ' Execute method to install some DDL.

Second, get a list of strings and use the Java 8 stream to split them into a first/last name pair in a Java array.

Then use the BatchUpdate method of JdbcTemplate to install some records in the newly created table. The first parameter of a method call is a query string, and the last parameter (an object array) contains the "? "The variable of the character.

For single-insert statements, the JdbcTemplate "Insert method is good. But for multiple insertions, it's best to use BatchUpdate.

Use? Avoid parameters for SQL injection attacks by instructing the JDBC binding variable.

Finally, you use the Query method to search the table for qualifying records. You use again? " "parameter creates a parameter for the query and passes in the actual value when the call is made. The last parameter is the Java 8 lambda used to convert each result row into a new customer object.

Java 8 lambda can be well mapped to a single method interface, such as spring's rowmapper. If you are using Java 7 or earlier, you can easily insert an anonymous interface implementation and have the same method body as the body of the method contained in the lambda expression bodies, and it will have no effect in spring

4. Compile into an executable jar

You can use Gradle or maven to run the application from the command line. Or you can build an executable jar file that contains all of the required dependencies, classes, and resources, and run the file. This makes it easy to publish, release, and deploy services as applications across different environments throughout the development lifecycle.

We still use STS to quickly generate executable jars

F5 Refresh Project, we can see that the executable jar has been successfully generated under the target directory

If you are using Gradle, you can use the./gradlew Bootrun to run the application. Or you can build a build jar file using./gradlew. Then you can run the jar file:

Java-jar Build/libs/gs-relational-data-access-0.1.0.jar

If you are using MAVEN, you can use the./MVNW Spring-boot:run to run the application. Alternatively, you can build the jar file using the./MVNW Clean package. Then you can run the jar file:

Java-jar Target/gs-relational-data-access-0.1.0.jar

The above procedure creates a runnable jar. You can also choose to build a classic war file.

You should be able to see the following output:

Source: Click to view

Spring Boot has a number of features for configuring and customizing connection pooling, such as connecting to an external database rather than a memory database. For more detailed information, see the User's Guide.

5. Spring uses JDBC to access relational data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.