我在新创建的对象的id上得到了这个空指针异常,即使它应该是自动生成的。
@Entity
@Table(name = "REQUEST")
@EntityListeners(DatabaseListener.class)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "requestId", scope = Request.class)
public class Request implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "REQUEST_ID", nullable = false)
private Long requestId;
@Column(name = "REQUEST_NAME")
private String name;
@Column(name = "CATEGORY")
private String category;
@Column(name = "REQUEST_MESSAGE")
private String requestMessage;
@Column(name = "CREATED_ON")
private Date createdOn;
@ManyToOne
private User createdBy;
@ManyToOne
private User assignedTo;
@ManyToOne
private Status status;
@OneToMany(mappedBy = "request", fetch = FetchType.EAGER)
private List<Response> replies;
我正在呼叫的终端......
@RequestMapping(value = "/requests/addRequest", method = RequestMethod.POST)
public ResponseEntity<Request> addRequest(@RequestBody final Request request) {
if(request.getStatus() == null){
request.setStatus(request.getAssignedTo() == null ? statusRepo.findByType(StatusType.UNASSIGNED) : statusRepo.findByType(StatusType.ASSIGNED));
}
final Request saved = requestRepo.save(request);
return new ResponseEntity<>(saved, HttpStatus.CREATED);
}
如果需要,我可以添加更多其他类。但我无法弄清楚为什么requestId将为null。我从一个应用程序调用了这个enpoint并传递了一个Request
对象,所以很明显它是null但是当它进入数据库时它不应该为null。对?
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: (was java.lang.NullPointerException) (through reference chain: Request["requestId"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: Request["requestId"])
...
Caused by: com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain:Request["requestId"])
...
Caused by: java.lang.NullPointerException: null
at com.fasterxml.jackson.annotation.ObjectIdGenerator$IdKey.<init>(ObjectIdGenerator.java:125) ~[jackson-annotations-2.4.0.jar:2.4.0]
编辑:要清楚,我知道空指针异常是什么,我知道requestId是null并且导致了问题,所以我不认为这是一个重复的问题。我不明白的是为什么它是空的。它应该是自动生成的,但正如Jason指出的那样,我可能必须首先确定id应用程序端。
答案 0 :(得分:1)
不是最优雅的,但到目前为止我能找到的唯一解决方案。
我创建了一个新的端点,创建了一个空白Request
,将其保存在数据库中并将其返回给应用程序。这样,应用程序现在有一个空白Request
,其中包含真实且正确的ID。
然后在我的addRequest
端点中,我对该ID进行查询,而不是创建新的请求,而只是更新现有的请求。
编辑:实际上addRequest
方法将保持不变,因为数据库将只更新现有条目。