2017-02-15 48 views
0

我正在用Spring Boot和MySQL製作RESTful API Web服務。在頂層,我有一個實體sites。在第二級實體floors。每個site可能有幾個floors。 這裏是Floors類:使用MySQL進行Spring-Boot-RESTful API web服務:SQL錯誤:1054,SQLState:42S22,'字段列表'中的未知列

@Entity 
public class Floors { 

    @Id 
    private String id; 
    private String floor; 

    @ManyToOne 
    private Sites site; 

    public Sites getSite() { 
     return site; 
    } 

    public void setSite(Sites site) { 
     this.site = site; 
    } 

    public Floors(){} 

    public Floors(String id, String floor, String siteId) { 
     super(); 
     this.id = id; 
     this.floor = floor; 
     this.site = new Sites(siteId, "", ""); 
    } 

//getters and setters 

這裏是FloorsController

@RestController 
public class FloorsController { 

    @Autowired 
    private FloorsService floorsService; 

    @RequestMapping("/api/sites/{id}/floors") 
    public List<Floors> getAllFloors(@PathVariable String id){ 
     return floorsService.getAllFloors(id); 
    } 

    @RequestMapping(method = RequestMethod.POST, value = "/api/sites/{siteId}/floors") 
    public void addFloor(@RequestBody Floors floor, @PathVariable String siteId){ 
     floor.setSite(new Sites(siteId, "","")); 
     floorsService.addFloor(floor); 
    } 

} 

這裏是SitesService

@Service 
public class SitesService { 

    @Autowired 
    private SitesRepository sitesRepository; 

    public List<Sites> getAllSites(){ 
     List<Sites> sites = new ArrayList<>(); 
     sitesRepository.findAll() 
       .forEach(sites::add); 
     return sites; 
    } 

    public void addSite(Sites site){ 
     sitesRepository.save(site); 
    } 
} 

這裏是我的FloorsRepository

public interface FloorsRepository extends CrudRepository<Floors, Integer> { 

    public List<Floors> getFloorsBySiteId(String siteId); 
} 

然後在MySQL Workbench中,我創建了兩個表:

CREATE TABLE `employeelocator1`.`sites` (
    `id` VARCHAR(45) NOT NULL, 
    `site` VARCHAR(45) NULL, 
    PRIMARY KEY (`id`)); 

CREATE TABLE `employeelocator1`.`floors` (
    `id` VARCHAR(45) NOT NULL, 
    `floor` VARCHAR(45) NULL, 
    `siteId` VARCHAR(45) NULL, 
    PRIMARY KEY (`id`), 
    INDEX `FK_siteId_idx` (`siteId` ASC), 
    CONSTRAINT `FK_siteId` 
    FOREIGN KEY (`siteId`) 
    REFERENCES `employeelocator1`.`sites` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION); 

當我使用/api/sites得到它運作良好,所有站點的列表。但是,當我試圖讓使用/api/sites/1/floors在現場#1所有樓層的名單,我得到一個錯誤:

o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22 
o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'floors0_.site_id' in 'field list' 

它是由於錯誤的東西與我的數據庫和表?或者代碼有問題?

回答

0

找到了我的問題的答案。 FK在floors表應該被命名爲site_id,而不是siteId

0

Sites Entity,你也可以這樣定義來解決問題:

@Id 
@Column(name = "id", nullable = false) 
private String site_id; 
相關問題