我正在尝试解决保存具有一对一关系的实体的问题。
我有一个Tenant对象,它有一个字段Apartment。每次当我尝试保存一个新的租户对象时,我会得到400错误,尽管params对我来说似乎没问题:
如果我从输入表单中删除了公寓,则可以毫无问题地保存租户。
如何保存实体及其关系???
RestController
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> create(@Valid @RequestBody Tenant tenant, BindingResult result) {
if (result.hasErrors()) {
ApiResponse message = new ApiResponse();
message.setErrors(result.getFieldErrors());
return new ResponseEntity<ApiResponse>(message, HttpStatus.UNPROCESSABLE_ENTITY);
}
try {
service.saveTenant(tenant);
} catch (ConstraintViolationException e) {
result.rejectValue("apartmentNumber", "error.apartment", DUPLICATE_VALUE);
Map<String, String> test = new HashMap<>();
for (FieldError fieldError : result.getFieldErrors()) {
test.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return new ResponseEntity<Map<String, String>>(test, HttpStatus.CONFLICT);
}
return new ResponseEntity<Tenant>(tenant, HttpStatus.CREATED);
}
JSP页面 - 有问题的输入
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Mieszkanie</label>
<div class="col-sm-9">
<select name='apartment' ng-model="ctrl.tenant.apartment" ng-required='true' class="form-control">
<option ng-repeat="item in ctrl.apartments" value="{{item}}"
ng-selected="ctrl.tenant.apartment.description == item.description">
{{item.description}}</option>
</select>
<p class="help-block">
<span class='error' ng-show="myForm.tenant_apartment.$invalid">
Pole wymagane</span> <span class='error'>{{errors.tenant_apartment}}</span>
</p>
</div>
</div>
答案 0 :(得分:0)
您的租户类是否具有Appartment as Set type的成员变量。 我的意思是
public class Tenant implements Serializable { private Set<Appartment> appartment; ..... ..... }