简体   繁体   English

Spring Boot-使用MySql访问构建RESTful Web服务

[英]Spring Boot - Building a RESTful Web Service with MySql access

I send a request to the rest-api to store a object into mysql database. 我向rest-api发送请求以将对象存储到mysql数据库中。

Which step is missing that i can store via Jpa the objects into my database? 我可以通过Jpa将对象存储到数据库中缺少哪一步?

Here is the Rest-Controller 这是休息控制器

@RestController
public class OwnerRestController {
    @Autowired
    private final OwnerRestRepository repo;

    public OwnerRestController(OwnerRestRepository repo) {this.repo = repo;}

    @RequestMapping(value="/owner/add", method=RequestMethod.POST)
    public Owner create(@RequestBody Map<String, String> body){
        Owner o = new Owner();
        o.setFirstName(body.get("firstName"));
        o.setLastName(body.get("lastName"));
        o.setAddress(body.get("address"));
        o.setCity(body.get("city"));
        o.setTelephone(body.get("telephone"));
        this.repo.save(o);
        return o;
    }
}

Here is the Repository Interface 这是存储库接口

public interface OwnerRestRepository extends CrudRepository<Owner,integer>{}

Here is the JSON-Object Owner 这是JSON对象所有者

{
    "firstName":"fname",
    "lastName":"lname",
    "address":"address1",
    "city":"city1",
    "telephone":"4711"
}

Server Response 服务器响应

{
    "id": 11,
    "firstName": "fname",
    "lastName": "lname",
    "address": "address1",
    "city": "city1",
    "telephone": "4711"
}

What's wrong in the code that the data can't be stored in the database? 无法将数据存储在数据库中的代码有什么问题?

Best regards, Mux 最好的问候,Mux

By default Spring runs the in-memory database - H2 , so your items only exist when your application is running. 默认情况下, Spring运行内存数据库H2 ,因此您的项目仅在应用程序运行时存在。
To persist your data you need to configure the application to use another database. 要保留数据,您需要将应用程序配置为使用另一个数据库。

To query H2 you can also use The H2 Console Application 要查询H2您还可以使用H2控制台应用程序

For example if you want to configure MySQL you should have add following configuration options to your application.properties file. 例如,如果要配置MySQL ,则应在application.properties文件中添加以下配置选项。

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

In case your are using application.yml 如果您正在使用application.yml

spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/test
    username: dbuser
    password: dbpass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM