在Spring Boot中手动为JPA插入ID

时间:2018-12-16 02:23:18

标签: java spring spring-boot jpa

如何在Spring Boot中为此JPA实体手动插入ID?我不希望ID自动生成。我尝试使用邮递员发送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);
    }

}

2 个答案:

答案 0 :(得分:0)

您的安装员可能出了些问题。尝试再次生成它们。

答案 1 :(得分:0)

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