SpringGuide:Accessing data with MySQL

26 篇文章 0 订阅

这个例子很不错,用实际的数据库MySQL,而不是用内存数据库,内存数据库估计大家平时一般也不会用,总感觉有点虚。

Starting with Spring Initializr

访问初始化程序的应用网站:https://start.spring.io/

依赖是三个分别是:1、 Spring Web Starter, 2、Spring Data JPA,3、 MySQL Driver 

应用程序取名字:accessing data mysql

点击Gnerate 生成一个下载包。下载后用SpringToolSuite 在本地打开。

Create the Database(创建数据库)

创建数据库,你如果有数据库,就不用创建了,用就可以了。

创建用户,给一切权限。

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

这些你也可以在MySQL的图形界面去做,创建一个用户给它个DBA权限就可以了。

Create the application.properties File(创建配置文件)

这个就是配置文件,配置数据源,连接字符串什么的,具体如下:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
#jdbc:mysql://localhost:3306/library?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai

spring.datasource.username=springlcg
spring.datasource.password=XXXXXXXXXXXX

密码根据实际情况自己改了。这一句中;spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC 问号后面是后加的,要不然会出错。

原文解释了一下几个参数的意义:MySQL默认就是none,这里用update,就是说根据给定的实体结构,Hibernate会更改库结构。

  • none: The default for MySQL. No change is made to the database structure.

  • update: Hibernate changes the database according to the given entity structures.

  • create: Creates the database every time but does not drop it on close.

  • create-drop: Creates the database and drops it when SessionFactory closes.

Create the @Entity Model(创建实体模型)

创建类:User.java

package com.example.accessingdatamysql;

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

Create the Repository(创建资料库)

创建类:UserRepository.java

package com.example.accessingdatamysql;

import org.springframework.data.repository.CrudRepository;

import com.example.accessingdatamysql.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, Integer> {

}

Spring automatically implements this repository interface in a bean that has the same name (with a change in the case — it is called userRepository).

Spring 自动实现这个repository接口在一个bean中,bean的名字就是小写后的:userRepository

Create a Controller(创建控制器)

创建类MainController.java

package com.example.accessingdatamysql;

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

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

  @PostMapping(path="/add") // Map ONLY POST 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();
  }
}

Create an Application Class

不需要做什么这里。

Build an executable JAR

这一步可以略过。

Test the Application

在IDE中,

runas spring boot app ,如果不出错就可以运行起来。

进入到cmd命令行中:运行下面的命令

$ curl localhost:8080/demo/add -d name=First -d email=someemail@someemailprovider.com

这个命令添加一个用户。curl是个模拟工具。

会返回一个saved,说明成功了。 去MySQL里面看看去

会看到新增的一行叫First的用户 。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值