【发布时间】:2018-12-16 02:23:18
【问题描述】:
如何在 Spring Boot 中手动为该 JPA 实体插入 id?我不希望自动生成 id。我尝试使用邮递员将此 JSON 对象发送到 RestController 发送 POST 请求:
{
"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);
}
}
【问题讨论】:
-
如果实体的主键字段没有用@GeneratedValue 标记,则不会自动生成主键值,应用程序负责通过初始化主键字段来设置主键。这必须在任何尝试持久化实体对象之前完成
-
在调用 cityRepository.save() 之前尝试打印对象 City;
-
您是否调试过您的代码。 id 字段在保存前是否有值。似乎在 json 中您将 id 作为字符串传递,可能是未设置为城市的值。尝试传递不带 " 的数字,例如 "id":1
-
id 在 save() 之后没有值了。
-
我可以看看你的
City课程吗?
标签: java spring spring-boot jpa