繁体   English   中英

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

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

我向rest-api发送请求以将对象存储到mysql数据库中。

我可以通过Jpa将对象存储到数据库中缺少哪一步?

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

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

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

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

无法将数据存储在数据库中的代码有什么问题?

最好的问候,Mux

默认情况下, Spring运行内存数据库H2 ,因此您的项目仅在应用程序运行时存在。
要保留数据,您需要将应用程序配置为使用另一个数据库。

要查询H2您还可以使用H2控制台应用程序

例如,如果要配置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

如果您正在使用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