Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am trying to resolve a problem with saving an entity that has one-to-one relationship.

I have a Tenant object that has a field Apartment. Every time when I try to save a new Tenant object I get 400 error although the params seems ok to me:

Params:
Params

Response: Response

If I remove Apartment from the input form the Tenant gets to be saved without a problem.

How can I save an entity along with it's relation???

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 page - the input in question

<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>
share|improve this question

Is your Tenant class has a member variable of Appartment as Set type. I mean

public class Tenant implements Serializable {

    private Set<Appartment> appartment;
    .....
    .....
}
share|improve this answer
    
Its a one to one relationship so it's just @OneToOne private Apartment apartment; – Maciej Sep 18 at 12:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.