Enterprise Distribution Micro Service Cloud Springcloud springboot MyBatis (vii) use JdbcTemplate to access the database in Spring boot

Source: Internet
Author: User
Tags assert

This article describes an example of configuring a data source and writing data access through JdbcTemplate on a spring boot basis.

Data Source Configuration

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

First, in order to connect to the database you need to introduce JDBC support, in which the pom.xml following configuration is introduced:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId> Spring-boot-starter-jdbc</artifactid></dependency>

  

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 pom.xml introduce the following configuration in to use Hsql

<dependency>    <groupId>org.hsqldb</groupId>    <artifactid>hsqldb</artifactid >    <scope>runtime</scope></dependency>

  

Connecting a production data source

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

<dependency>    <groupId>mysql</groupId>    <artifactid>mysql-connector-java</ Artifactid>    <version>5.1.21</version></dependency>

  

src/main/resources/application.propertiesConfiguring data source information in

Spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username= Dbuserspring.datasource.password=dbpassspring.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.

spring.datasource.jndi-name=java:jboss/datasources/customers
manipulating databases with JdbcTemplate

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

For example: We are creating User tables, including properties name , and age , below, writing data Access objects and unit test cases.

  • Defines an abstract interface that contains inserts, deletes, and queries UserService
    Public interface UserService {    /**     * Adds 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 ();

      

  • The
  • implements the data access operations defined in UserService through JdbcTemplate
     @Servicepublic class    Userserviceimpl implements UserService {@Autowired private jdbctemplate jdbctemplate; @Override public void Create (String name, Integer age) {jdbctemplate.update ("insert into USER (name, age) values    (?,?) ", name, age); } @Override public void Deletebyname (String name) {jdbctemplate.update ("delete from USER where name =?", NA    ME); } @Override Public Integer getAllUsers () {return Jdbctemplate.queryforobject ("SELECT count (1) by USER", in    Teger.class);    } @Override public void Deleteallusers () {jdbctemplate.update ("delete from USER"); }} 

  • The
  • creates unit test cases for UserService and verifies the correctness of database operations by creating, deleting, and querying.
     @RunWith (springjunit4classrunner.class) @SpringApplicationConfiguration ( Application.class) public class Applicationtests {@Autowiredprivate userservice userserivce; @Beforepublic void SetUp () {//Prepare, empty user table Userserivce.deleteallusers ();} @Testpublic 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);//Check database, There should be 5 users assert.assertequals (5, Userserivce.getallusers (). Intvalue ());//Delete two user userserivce.deletebyname ("a"); Userserivce.deletebyname ("E");//Check the database, there should be 5 users assert.assertequals (3, Userserivce.getallusers (). Intvalue ());}} 
    The JdbcTemplate described above in

    is just a few of the most basic operations, and more use of other data access operations is available at: JdbcTemplate API

    SOURCE

  • From the simple example above, we can see that the configuration of accessing the database under Spring boot still holds the framework's original intention: simple. 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 directly into your own object.

Enterprise Distribution Micro Service Cloud Springcloud springboot MyBatis (vii) use JdbcTemplate to access the database in Spring boot

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.