springboot mysql操作

2020-03-20  本文已影响0人  知识分享share

1.Spring Web Starter,Spring Data JPA和MySQL Driver依赖项安装
2.目录结构


微信截图_20200320123030.png

3.User.java

package com.example.demo2.demo3;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    private String email;
    /**
     * @return the id
     */
    public Integer getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }
    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

}

4.UserRepository.java

package com.example.demo2.demo3;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User,Integer>{

}

5.MainController.java

package com.example.demo2.demo3;

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
@RequestMapping(path="/demo")
public class MainController{

    @Autowired
    private UserRepository userRepository;

    @PostMapping(value="/add")
    public @ResponseBody String addNewUser(@RequestParam String name,@RequestParam String email){
        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "saved";
    }
    
    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers(){
        return userRepository.findAll();
    }
    
}

6.application.properties

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_demo?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

7.test.http

POST http://127.0.0.1:8080/demo/add HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name="hx"&email="qq@qq.com"

###
GET http://127.0.0.1:8080/demo/all HTTP/1.1
上一篇 下一篇

猜你喜欢

热点阅读