I've OneToMany
relation between User
& Address
and ManyToOne
relation with EmploymentType
.
@Entity
public class User {
//..
private String name;
@ManyToOne
private EmploymentType employmentType;
@OneToMany(mappedBy = "user")
private Set<Skill> skills = new HashSet<>();
//..
}
@Entity
public class Skill {
//..
@ManyToOne
private User user;
//..
}
@Entity
public class EmploymentType {
//..
@ManyToOne
private User user;
//..
}
@RepositoryRestController
public class CustomUserController {
private UserRepository userRepository;
@PostMapping(path = "/users/createUserWithEmploymentType")
public @ResponseBody String createUserWithEmploymentType(@RequestBody EntityModel<User> users) {
System.out.println(users);
// ....
return "SUCCESS";
}
@PostMapping(path = "/users/createUserWithSkillBatch")
public @ResponseBody String createUserWithSkill(@RequestBody CollectionModel<EntityModel<User>> users) {
System.out.println(users);
// ....
return "SUCCESS";
}
}
I need to use custom RepositoryRestController
for some additional check before I persist the records.
curl -i -X POST -H "Content-Type:application/json" -d '{"name": "Kiran Kyle", "employmentType": "http://localhost:8080/api/v1/employmentTypes/1"}' http://localhost:8080/api/v1/users/createUserWithEmploymentType
This curl works.
curl -i -X POST -H "Content-Type:application/json" -d '[{"name": "Kiran Kyle", "skill": ["http://localhost:8080/api/v1/skills/1", "http://localhost:8080/api/v1/skills/2"]}]' http://localhost:8080/api/v1/users/createUserWithSkillBatch
This does not giving error ...ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type
org.springframework.hateoas.CollectionModelfrom Array value (token
JsonToken.START_ARRAY); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type
org.springframework.hateoas.CollectionModelfrom Array value (token
JsonToken.START_ARRAY)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]]
It seems when there is an array of HAL URI's, spring does not convert to entity object.
Adding an extra generic type to the function parameter works (Don't know how. I guess List makes resource URI's to be resolved before persisting the entity)
public class Items<T> {
private List<T> items;
}
public @ResponseBody String createUserWithSkill(@RequestBody CollectionModel<EntityModel<Items<User>>> users)