Spring Boot Learning (vii) Web applications use JdbcTemplate to Access database __ Database

Source: Internet
Author: User
Tags assert access database mysql database

We have been using the SSM framework to write Web sites that Access database types, and app,web sites need to have databases to store data.

Let's take a look at the Springboot operation database using JdbcTemplate;

data Source configuration in the configuration file

When we access the database, we need to first configure a data source, the following describes several different ways of database configuration.

Embedded Database Support

Embedded databases are typically used for development and test environments and are not recommended for production environments. Spring boot provides an automatically configured embedded database with H2, HSQL, Derby, which you do not need to provide any connection configuration to use.

For example, we can introduce the following configuration to use Hsql in Pom.xml;

Connecting a production data source

Take MySQL database as an example, first introduce the MySQL connection dependency package, add in Pom.xml:

First, in order to connect to a database, you need to introduce JDBC support and introduce the following configuration in Pom.xml:

Here we are using 1.3.2, he and 1.5.8 tests note difference before the blog has been described here is not more said; see Pom file

<parent> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-parent</artifactid> <version>1.3.2.RELEASE</version> <relativePath/> <!--lookup parent from repository--</parent> <properties> <project.build.sourceencoding>u Tf-8</project.build.sourceencoding> <java.version>1.8</java.version> </properties> < dependencies> <dependency> <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SPR ing-boot-starter</artifactid> </dependency> <dependency> <groupid>org.springframework.boo T</groupid> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> & lt;/dependency> <dependency> <groupId>mysql</groupId> <artifactid>mysql-connector-java </artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactid>spri
			ng-boot-starter-jdbc</artifactid> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-maven-plugi n</artifactid> </plugin> </plugins> </build>

Configuring data source information in Src/main/resources/application.properties

Spring.datasource.url=jdbc:mysql://localhost:3306/test
Spring.datasource.username=root
Spring.datasource.password=root
Spring.datasource.driver-class-name=com.mysql.jdbc.driver

connecting Jndi data sources

When you deploy your application on an application server and want the data source to be managed by the application server, you can introduce a JNDI data source using the following configuration. We can do this:

	
Spring.datasource.jndi-name=java:jboss/datasources/customers

manipulating databases with JdbcTemplate

Spring's jdbctemplate is automatically configured, and you can use @autowired directly to inject it into your own bean.

For example: We are creating a user table that contains the properties name, age, and the following to write data Access objects and unit test cases. Defines an abstract interface that contains inserts, deletes, and queries UserService

/**
 *  Xiao Jin GG */public
interface UserService {

    /**
     * Add a user
     * @param name
     * @param age
     *
    /void Create (String name, Integer age);

    /**
     * Delete a user by name High
     * @param name
     *
    /void Deletebyname (String name);

    /**
     * Get user Total
     *
    /Integer getAllUsers ();

    /**
     * Delete all users
     *
    /void Deleteallusers ();
Implementing data access operations defined in Userserviceimpl with JdbcTemplate
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.jdbc.core.JdbcTemplate;

Import Org.springframework.stereotype.Service; /** * into GG * * @Service public class Userserviceimpl implements UserService {@Autowired private JdbcTemplate J

    Dbctemplate; @Override public void Create (String name, Integer age) {jdbctemplate.update ("insert into USER (name, age) Valu
    Es (?,?) ", name, age); } @Override public void Deletebyname (String name) {jdbctemplate.update ("delete from USER where name =?")
    , name); } @Override Public Integer getAllUsers () {return Jdbctemplate.queryforobject ("SELECT count (1) from USER"
    , Integer.class);
    } @Override public void Deleteallusers () {jdbctemplate.update ("delete from USER"); }
}
Create unit test cases for UserService to verify the correctness of database operations by creating, deleting, and querying.
Import Com.didispace.service.UserService;
Import Org.junit.Assert;
Import Org.junit.Before;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.boot.test.SpringApplicationConfiguration;

Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Jin GG */@RunWith (Springjunit4classrunner.class) @SpringApplicationConfiguration (application.class) public class

	applicationtests {@Autowired private userservice userserivce;
	@Before public void SetUp () {//Prepare to empty user table userserivce.deleteallusers ();
		} @Test public void Test () throws Exception {//Insert 5 user userserivce.create ("a", 1);
		Userserivce.create ("B", 2);
		Userserivce.create ("C", 3);
		Userserivce.create ("D", 4);

		Userserivce.create ("E", 5);

		Database, there should be 5 users assert.assertequals (5, Userserivce.getallusers (). Intvalue ());
		Delete two user userserivce.deletebyname ("a");

		Userserivce.deletebyname ("E"); // Database, there should be 5 users assert.assertequals (3, Userserivce.getallusers (). Intvalue ());
 }

}

The jdbctemplate described above is only the most basic of several operations, and more other data access operations to use please refer to: JdbcTemplate API

here is just a simple example of the introduction; When using it, we only need to add database dependencies to the Pom.xml, and then configure the connection information in the application.properties, without needing to create the JdbcTemplate bean in the spring application and inject it into its own object.

Welcome everyone to Exchange learning Springboot,java and other fields of technology, Exchange groups: 587674051 Blog Source code is also in the inside



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.