Spring Boot using MySQL database

Introduction

  This article describes how to connect in Spring project, the MySQL database.
  The project uses the JPA and Hibernate Spring Data connected, the MySQL database, of course, this is just one way that you can use Spring JDBC or MyBatis.
  Spring Data is a sub-project the JPA Spring Data is mainly used to simplify data for access layer, using Spring Data JPA can easily implement CRUD, paging, sorting, and so on. Spring Data has many sub-projects, in addition to Spring Data Jpa, there are the following sub-projects.

  • Spring Data Commons
  • Spring Data MongoDB
  • Spring Data Redis
  • Spring Data Solr
  • Spring Data Gemfire
  • Spring Data REST
  • Spring Data Neo4j

  Hibernate object-relational mapping framework is an open source, it had a very lightweight JDBC object package, it will POJO mapping relationship with a database table, is a fully automated ORM frameworks, Hibernate automatically generates SQL statements, automatically, so that the Java programmer can use arbitrary object programming thinking to manipulate the database. Hibernate can be used in any occasion using JDBC, Java can be used in both client program can also be used in Servlet / JSP Web application, the most revolutionary is, Hibernate can replace EJB CMP in the application of the J2EE architecture to complete the task of data persistence.
  This article describes how to use the Spring Data JPA and Hibernate to connect, the MySQL database.

ready

  First of all we need to do some preparation for MySQL process. We are going to create a database in MySQL db_example and create springuser users with all operating authority db_example database. Open MySQL, enter the following command:

MySQL >  the Create  Database db_example; - create a new database db_example 
MySQL >  the Create  the User  ' springuser ' @ ' localhost ' IDENTIFIED by  ' pwd123 ' ; - Create a new user springuser, password pwd123 
MySQL >  Grant  All  ON . db_example *  to  ' springuser ' @ ' localhost ' ; - give all springuser user's authority to operate the database db_example

Spring Boot program

. Step1 create a project spring_mysql, as well as the layout of the project:

mkdir spring_mysql
cd ./spring_mysql
touch build.gradle
mkdir -p src/main/java
mkdir -p src/main/resources
mkdir -p src/test/java
mkdir -p src/test/resources

Step2 write build.gradle

  build.gradle code is as follows:

buildscript 
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.0.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-accessing-data-mysql'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")

    // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...)
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'

    // Use MySQL Connector-J
    compile 'mysql:mysql-connector-java'

    testCompile('org.springframework.boot:spring-boot-starter-test')
}

In the Spring Boot projects mainly using spring-boot-starter-web, spring-boot-starter-data-jpa and mysql: mysql-connector-java to end the operation in the Web MySQL.

Step3 configuration properties file

  New src / main / resources / application.properties files, configuration related attributes, as follows:

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=pwd123

In the above code, the main operations for the new database (Create), as implemented in the corresponding database table does not exist. Localhost using MySQL database server db_example 3306 port, and set the user name and password.

Step4 written in Java files

  Create src / main / java / hello folder (package), User.java in the new folder, Hibernate the entity class will be automatically converted into a table in the database. User.java complete code is as follows:

package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

  In the UserRepository.java new folder, which code is as follows:

package hello;

import org.springframework.data.repository.CrudRepository;

import hello.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Long> {

}

This is a repository interface, which will be in Spring bean in automatically.
  MainController.java new folder in the above, as follows:

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import hello.User;
import hello.UserRepository;

@Controller    // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
    @Autowired // This means to get the bean called userRepository
               // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;

    @GetMapping(path="/add") // Map ONLY GET Requests
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }
}

This is a new controller Spring applications (Controller).
  Application.java new folder in the above, as follows:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

It was the Spring Boot project's main program entry.

Step5 create an executable jar package

cd spring_mysql
gradle build

After machining, the generated gs-accessing-data-mysql-0.1.0.jar in the build / libs folder.

Operation and test

  Spring Boot start the project by using the following command

java -jar build/libs/gs-accessing-data-mysql-0.1.0.jar

  In the browser test, enter the following URL:

localhost:8080/demo/add?name=Alex&email=alex@baidu.com
localhost:8080/demo/add?name=Jclian&email=github@sina.com
localhost:8080/demo/add?name=Bob&email=bob@google.com localhost:8080/demo/add?name=Cook&email=cook@apple.com localhost:8080/demo/add?name=Mark&email=mark@west.com 

Value of the parameter name and email program will resolve to a record in the database and stored in the user table, a browser interface as follows:

 
Data storage

Enter the URL in the browser localhost: 8080 / demo / all, you can just see us we insert into the record (JSON format) MySQL in:

 
Web page view data

Finally, we went to see the data in MySQL is inserted successful, the results as shown below:

 
View the data in MySQL

Guess you like

Origin www.cnblogs.com/chen8023miss/p/11430486.html