在Spring Boot中手动插入JPA的ID



如何在Spring引导中手动插入此JPA实体的id?我不希望id是自动生成的。我尝试使用poster发送POST请求,将此JSON对象发送到RestController:

{
"id":"1",
"name":"New York"
}

我收到一个错误,说我应该手动助理id。为什么它不接受我在请求中传递的id?

代码:

实体

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class City{
@Id
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long Id) {
this.Id = Id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} 
}

控制器:

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CityService{
private CityService cityService;
@Autowired
public void setCityService(CityService CityService) {
this.CityService = CityService;
}
@RequestMapping(method=RequestMethod.POST, value="/cities")
public void cities(@RequestBody City city){
cityService.save(city);
}
}

服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class CityService {
private CityRepository cityRepository;
@Autowired
public CityServiceImpl(CityRepository cityRepository) {
this.cityRepository= cityRepository;
}
@Override
public void saveCity(City city) {
CityRepository.save(city);
}
}

您的setter可能有问题。请尝试再次生成它们。

数据库中有一个结构不同的旧表。代码中没有错误。

最新更新