我是 Spring Boot 新手,我想知道如何允许响应 JSON 包含可为空的数据库列的空值。这是我的控制器、服务、存储库和模型:
package com.findersgame.questtracker.controller;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.findersgame.questtracker.model.MapArea;
import com.findersgame.questtracker.service.MapAreaService;
@RestController
public class MapAreaController {
private MapAreaService mapAreaService;
public MapAreaController(MapAreaService mapAreaService) {
super();
this.mapAreaService = mapAreaService;
}
@PostMapping("selected_map_areas")
public List<MapArea> selectedMapAreas(@RequestBody List<Integer> selectedMapAreas) {
return mapAreaService.selectedMapAreas(selectedMapAreas);
}
}
package com.findersgame.questtracker.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.findersgame.questtracker.model.MapArea;
import com.findersgame.questtracker.repository.MapAreaRepository;
@Service
public class MapAreaService {
private MapAreaRepository mapAreaRepository;
public MapAreaService(MapAreaRepository mapAreaRepository) {
super();
this.mapAreaRepository = mapAreaRepository;
}
public List<MapArea> selectedMapAreas(List<Integer> selectedIds) {
return mapAreaRepository.findAllById(selectedIds);
}
}
package com.findersgame.questtracker.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.findersgame.questtracker.model.MapArea;
public interface MapAreaRepository extends JpaRepository<MapArea, Integer> {
}
package com.findersgame.questtracker.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "map_areas")
public class MapArea {
@Id
private int id;
@Column
private int mapTabId;
@Column
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMapTabId() {
return mapTabId;
}
public void setMapTabId(int mapTabId) {
this.mapTabId = mapTabId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我的问题是,当我用 body
http://localhost:8080/selected_map_areas
调用 [14, 15, 16]
时,我收到以下错误。
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Cannot invoke "java.lang.Integer.intValue()" because "this.mapTabId" is null]
我想这是有道理的,因为在数据库中,id 15 和 16 的
map_tab_id
值都是 null
。我猜我在上面的类/接口之一中缺少注释,但我没有能够找到哪一个。
在java中int是值类型,Integer是类类型。 所以 int 不能为 null,Integer 可以为 null。 将mapTabId的类型更改为Integer