我有两个实体,分别通过@OnToOne关系连接到父级和子级:
public class Child implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@JsonProperty(access= Access.READ_ONLY)
private Long id;
@OneToOne(cascade=CascadeType.REMOVE, fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
private Parent parent;
//other attributes
//setters and getters
}
public class Parent implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@JsonProperty(access= Access.READ_ONLY)
private Long id;`
//other attributes
//setters and getters
}
我正在尝试为子实体创建RESTFul @Post方法,其中客户端(最终用户)必须提供有效的父代ID才能创建新的子代(必须先创建父代,然后客户端应提供
仅创建父母的ID,而不是创建新孩子的整个父属性。下面是我的帖子方法
@POST
@ApiOperation(value = "Add a new child to the database")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "child created successfully."),
@ApiResponse(code = 400, message = "Invalid child supplied in request body"),
@ApiResponse(code = 409, message = "child supplied in request body conflicts with an existing child"),
@ApiResponse(code = 500, message = "An unexpected error occurred whilst processing the request")
})
public Response createChild(@ApiParam(required = true)Child child) {
if (child == null) {
throw new RestServiceException("Bad Request", Response.Status.BAD_REQUEST);
}
Response.ResponseBuilder builder;
try {
// Go add the new child.
childService.create(child);
// Create a "Resource Created" 201 Response and pass the child back in case it is needed.
builder = Response.status(Response.Status.CREATED).entity(child);
} catch (ConstraintViolationException ce) {
//Handle bean validation issues
Map<String, String> responseObj = new HashMap<>();
for (ConstraintViolation<?> violation : ce.getConstraintViolations()) {
responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
}
throw new RestServiceException("Bad Request", responseObj, Response.Status.BAD_REQUEST, ce);
} catch (Exception e) {
// Handle generic exceptions
throw new RestServiceException(e);
}
log.info("createChild completed. child = " + child.toString());
return builder.build();
}
我对孩子的JSON表示具有类似的属性(其中 parent 指代父id)
{
"Parent": 0,
...
}
当我测试我的post方法时,这里的问题是参数中的子对象始终为null !!,因为我试图获取该子对象的自动生成的ID(child.getId()),并且它为null。
那么我该如何为两个相关实体创建一个post方法,其中客户端应仅提供现有父实体的ID?