我向rest-api发送请求,将对象存储到mysql数据库中。
缺少哪一步我可以通过Jpa将对象存储到我的数据库中?
这是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;
}
}
这是存储库接口
public interface OwnerRestRepository extends CrudRepository<Owner,integer>{}
这是JSON对象所有者
{
"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
,您还可以使用The H2 Console Application
例如,如果要配置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