I have a database with one table named person:
id | first_name | last_name | date_of_birth ----|------------|-----------|--------------- 1 | Tin | Tin | 2000-10-10
There is a JPA object named Person that maps to this table:
@Entity @XmlRootElement(name = "person") @XmlAccessorType(NONE) public class Person { @Id @GeneratedValue private Long id; @XmlAttribute(name = "id") private Long externalId; @XmlAttribute(name = "first-name") private String firstName; @XmlAttribute(name = "last-name") private String lastName; @XmlAttribute(name = "dob") private String dateOfBirth;
The entity is also annotated with JAXB annotations to allow the loading of XML into HTTP requests for mapping to object instances.
I want to implement an endpoint for retrieving and updating an object with a given id .
According to this answer to a similar question , all I have to do is implement the handler method as follows:
@RestController @RequestMapping( path = "/persons", consumes = APPLICATION_XML_VALUE, produces = APPLICATION_XML_VALUE ) public class PersonController { private final PersonRepository personRepository; @Autowired public PersonController(final PersonRepository personRepository) { this.personRepository = personRepository; } @PutMapping(value = "/{person}") public Person savePerson(@ModelAttribute Person person) { return personRepository.save(person); } }
However, this does not work as expected, which can be confirmed by the following unsuccessful test case:
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT) public class PersonControllerTest { @Autowired private TestRestTemplate restTemplate; private HttpHeaders headers; @Before public void before() { headers = new HttpHeaders(); headers.setContentType(APPLICATION_XML); }
The first statement fails:
java.lang.AssertionError: Expected: "Tin Tin" but: was "Tin" Expected :Tin Tin Actual :Tin
In other words:
- There are no server-side exceptions (status code
200 ) - Spring successfully loads Person instance using
id=1 - But its properties are not updated.
Any ideas what I'm missing here?
Note 1
The solution provided here does not work.
Note 2
Full working code demonstrating the problem is provided here .
More details
Expected Behavior:
- Download an instance of Person using
id=1 - Fill the properties of the loaded face object with the XML payload using
Jaxb2RootElementHttpMessageConverter or MappingJackson2XmlHttpMessageConverter - Pass it to the controller action handler as its
Person argument
Actual behavior:
- An instance of Person is loaded with
id=1 - Instance properties are not updated according to XML in the request payload
- The properties of the face instance passed to the controller handler method are not updated