The H2DATABSE example is shown here, so a brief introduction to H2database related knowledge
The H2 database is an open-source relational database.
H2 is an embedded database engine, written in the Java language, not limited by the platform, while H2 provides a very convenient web console for manipulating and managing database content. It also provides compatibility mode and can be compatible with a number of mainstream databases, so it is very convenient to use H2 as a development-time database.
H2 Database Features:
Short and lean.
Java, which can be compiled using GCJ and ikvm.net.
Both Web and embedded versions are supported, plus a memory version is available.
There are better compatibility, support for a fairly standard SQL standard, support clusters.
Provides a JDBC, ODBC access interface that provides a very friendly web-based database management interface.
Here next JdbcTemplate, the reason will appear jdbctemplate, I personally add some of my own ideas, the traditional JDBC high coupling and a lot of repetitive additions and deletions, so that the upgrade of the JDBC version of the birth, this and MyBatis plus has a common feature. And JdbcTemplate is just seeing this and upgrading to JDBC.
For the JdbcTemplate example, you can refer to the example written by this friend: https://www.cnblogs.com/janes/p/6971839.html
Below is a reference to his introduction to JdbcTemplate:
JdbcTemplate is the most basic spring JDBC template that supports simple JDBC database access and query based on index parameters.
Spring Data Access templates: In the course of database operations, a large part of the repetitive work, such as transaction control, management resources, and handling exceptions, Spring's template classes handle these fixed parts. At the same time, application-related data access is handled in the implementation of callbacks, including statements, binding parameters, and collation results. In this way, we only need to care about our own data access logic.
The spring JDBC Framework takes care of resource management and exception handling, simplifying the JDBC code, and we just need to write the necessary code to read and write data from the database.
First, import dependency
<?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& Gt;org.springframework.boot</groupid> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> </parent> <properties> <java.version>1.8</j ava.version> </properties> <dependencies> <dependency> <GROUPID>ORG.SPR Ingframework.boot</groupid> <artifactId>spring-boot-starter-jdbc</artifactId> </DEP endency> <dependency> <groupId>com.h2database</groupId> <ARTIFACTID&G T;h2</artifactid> </dependency> </dependencies> <build> <plugins> <plugin> <groupid>org.spri Ngframework.boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId> & Lt;/plugin> </plugins> </build></project>
Ii. Preparation of Entities
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; } @Override PublicString toString () {returnString.Format ("customer[id=%d, Firstname= '%s ', lastname= '%s ']", ID, firstName, lastName); } 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; } }
Third, write the startup class
PackageHello;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;Importjava.util.Arrays;Importjava.util.List;Importjava.util.stream.Collectors; @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 ())); }}
The end result is:
the main() method uses the SpringApplication.run() spring boot method to start the application. Did you notice that there is not a single line of XML? There is no Web . xml file. This Web application is 100% pure Java, and you do not have to handle configuring any pipelines or infrastructure.
Spring Boot Support H2 , an in-memory relational database engine, and automatically creates a connection. because we are using spring-jdbc, Spring boot automatically creates one JdbcTemplate . the @Autowired JdbcTemplate field automatically loads it and makes it available.
this Application class implements the spring Boot CommandLineRunner , which means that it will run() Executes the method after the application context is loaded .
First, use JdbcTemplate’s `execute method to install some DDL .
Second, you get a list of strings and use the Java 8 stream to split them into firstname/lastname pairs in a Java array.
then use JdbcTemplate’s `batchUpdate Method installs some records in the newly created table . The first parameter of a method call is a query string, and the last parameter ( Object An array of s ) contains the "? "The variable for the query of the character.
Additional notes:
Java 8 Lambdas maps well 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 lambda expresion body, and it can use spring effortlessly.
Springboot Combat (iv) using JDBC and spring to access the database