I have two Entities one for Forms and another one for Fields. I created a class for compose the primary key of Fields so I have 2 properties as Primary Key the Number and the foreign key Form. I want to insert just the foreign key with one post so I made the post request like that:
@CrossOrigin
@PostMapping(value = "/field/{form_id}")
public Field addField(@PathVariable Integer form_id, @RequestBody Field body) {
Form result = formRepository.findById(form_id).orElse(null);
body.setForm(result);
fieldRepository.save(body);
return body;
}
My Form Class:
@Entity
public class Form {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@OneToMany(mappedBy="form", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private Set<Field> fields;
.
.
.
(Setter & Getter)
}
My Field Class
@Entity
@IdClass(FieldKey.class)
@JsonIgnoreProperties(
value = {"form"},
allowSetters = true
)
public class Field {
@Id
private Integer id;
@Id
@ManyToOne
@JoinColumn(name="form_id", nullable=false)
private Form form;
.
.
.
(Setter and Getter)
My FieldKey class
@JsonIgnoreProperties(
value = {"form"},
allowSetters = true
)
public class FieldKey implements Serializable {
private Integer id;
private Form form;
public FieldKey(Integer id, Form form) {
this.id = id;
this.form = form;
}
public FieldKey() {}
(Setter & Getter)
}
I expected to insert into the field table the new field with the relation Form_ID but I get this error:
org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.Integer' to required type 'com.model.Form' for property 'form'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Integer' to required type 'com.model.Form' for property 'form': no matching editors or conversion strategy found
If I use the embedded Id annotation instead using the class as EmbeddedKey it works without any problem but I don't like the json annotation because it will be:
{"fieldKey":{"id":1,"form_id":28}, etc...}