您的位置:首页 > 编程语言 > Java开发

Spring boot 实现 Accessing data with MySQL

2018-02-06 13:35 344 查看

Spring boot 实现 Accessing data with MySQL

用于总结spring guides里的实验 ,主要做翻译、理解

–by Lank

1. What you’ll build

You’ll create a MySQL database, build a Spring application and connect it with the newly created database


2. What you’ll need

MySQL

IDE

jdk1.8以上

Gradle 2.3+ or Maven 3.0+

本人使用的是Gradle + IDEA + MYSql5.7

3. DO

3.1 Build with Gradle

创建build.gradle,直接在IDEA里创建个gradle项目,重写build.gradle即可。

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

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

jar {
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')
}


Spring Boot gradle plugin 提供了很多方便的特性:

Spring Boot Maven plugin 同样可提供如此特性

它收集类路径上的所有jar,并构建一个单一的、可运行的“ über-jar”,这使得它更方便地执行和传输服务。

Spring Boot 旨在帮助开发人员创建能直接运行的应用程序。为实现该目的,它将应用程序及其依赖项包装在一个可执行 JAR 中。

它搜索的 public static void main() 方法来标记为可运行的类。

它提供了一个内置的依赖解析器,用于设置版本号以匹配 Spring Boot 的依赖。您可以覆盖任何你想要的版本,但它会默认选择的 Boot 的版本集。

3.2 Build with your IDE

Create a new database

mysql> create database db_example; -- Create the new database
mysql> create user 'springuser'@'localhost' identified by 'ThePassword'; -- Creates the user
mysql> grant all on db_example.* to 'springuser'@'localhost'; -- Gives all the privileges to the new user on the newly created database


Create the application.properties file

在resource目录下新建application.properties,主要用于配置对MYSQL的连接和操作。

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


Create the @Entity model

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;
}

}


这是一个实体类,Hibernate会自动转换成表。

Create the repository

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> {

}


这是存储库接口,它将被Spring在一个bean中自动实现,这个bean的名称与更改的名称相同,bean名称将是userRepository

Create a new controller for your Spring application

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();
}
}


Make the application executable

src/main/java/hello/Application.java

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);
}
}


启动验证

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: