SpringBoot XML RestAPIs + MySQL – Post/Get/Put/Delete Requests Example

springboot-xml-restapi-mysql---feature-image

In the tutorial, Grokonez show you how to create SpringBoot XML RestAPIs and MySQL with Post/Get/Put/Delete requests using jaxb-api & jackson-dataformat-xml

Related posts:
How to use Spring JPA MySQL | Spring Boot

Technologies

– SpringBoot
– MySQL
– Postman Rest-Client

Practices

Project Structure ->

springboot-xml-restapi-mysql---spring-boot-project

Create SpringBoot project

– We use SpringToolSuite to create a SpringBoot project with below dependencies:


	org.springframework.boot
	spring-boot-starter-web



	org.springframework.boot
	spring-boot-starter-data-jpa



	com.fasterxml.jackson.dataformat
	jackson-dataformat-xml

      

	javax.xml.bind
	jaxb-api
	2.3.1

      

    mysql
    mysql-connector-java

– The jackson-dataformat-xml adds Jackson XML serializer and deserializer.

Model

– We use @JacksonXmlRootElement & @JacksonXmlProperty to create Customer.java model:

  • @JacksonXmlProperty is used to set an attribute of the element in the XML output.
  • @JacksonXmlRootElement is used to set the name for the XML output root element.
package com.ozenero.xmlrestapi.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@Entity
@Table(name = "customers")
@JacksonXmlRootElement(localName = "Customer")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JacksonXmlProperty(isAttribute = true)
    private Long id;

    @JacksonXmlProperty    
	@Column(name = "firstname")
	private String firstname;
 
    @JacksonXmlProperty
	@Column(name = "lastname")
	private String lastname;
    
    @JacksonXmlProperty
	@Column(name = "age")
    private int age;

    public Customer() {
    }

    public Customer(Long id, String firstname, String lastname, int age) {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstname() {
    	return firstname;
    }
    
    public void setFirstname(String firstName) {
    	this.firstname = firstName;
    }
    
    public String getLastname() {
    	return this.lastname;
    }
    
    public void setLastname(String lastName) {
    	this.lastname = lastName;
    }
    
    public int getAge() {
    	return this.age;
    }
    
    public void setAge(int age) {
    	this.age = age;
    }
}

– Create an Customers.java helper class:

package com.ozenero.xmlrestapi.model;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement
public class Customers{

    @JacksonXmlProperty(localName = "Customers")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List customers = new ArrayList();

    public List getCustomers() {
        return customers;
    }

    public void setCustomers(List customers) {
        this.customers = customers;
    }
}

-> We use @JacksonXmlProperty & @JacksonXmlElementWrapper annotations to set a list of Customer to be elements of Customers element in XML output.

JPA Repository

– Create JPA repository CustomerRepository.java ->

package com.ozenero.xmlrestapi.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.ozenero.xmlrestapi.model.Customer;

@Repository
public interface CustomerRepository extends CrudRepository {
}
Controller RestAPIs

– We create 4 RestAPIs with Post/Get/Put/Delete XML request-mapping:

package com.ozenero.xmlrestapi.controller;

import java.util.List;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ozenero.xmlrestapi.model.Customer;
import com.ozenero.xmlrestapi.model.Customers;
import com.ozenero.xmlrestapi.repository.CustomerRepository;

@RestController
@RequestMapping("/api")
public class CustomerRestAPIs {
	
    @Autowired
    private CustomerRepository customerRepository;

    @PostMapping(value="/customer", produces=MediaType.APPLICATION_XML_VALUE)
	public Customer postCustomer(@RequestBody Customer customer) {
		return customerRepository.save(customer);
	}
    
    @GetMapping(value="/customer", produces=MediaType.APPLICATION_XML_VALUE)
    public Customers getAllCustomers() {
        List customer = (List) customerRepository.findAll();
        Customers customers = new Customers();
        customers.setCustomers(customer);

        return customers;
    }
    
    @GetMapping(value="/customer/{id}", produces=MediaType.APPLICATION_XML_VALUE)
    public Customer getCustomerById(@PathVariable Long id) {
    	Optional optCustomer = customerRepository.findById(id);
    	
    	if(optCustomer.isPresent()) {
    		return customerRepository.findById(id).get();
    	}
    	
    	throw new RuntimeException("Not Found a customer with id = " + id);
    }
    
    @PutMapping(value="/customer/{id}", produces=MediaType.APPLICATION_XML_VALUE)
    public Customer putCustomer(@PathVariable Long id,
            @Valid @RequestBody Customer customerUpdated) {
    	
    	return customerRepository.findById(id)
    			.map(customer -> {
                    customer.setFirstname(customerUpdated.getFirstname());
                    customer.setLastname(customerUpdated.getLastname());
                    customer.setAge(customerUpdated.getAge());
                    return  customerRepository.save(customer);
                }).orElseThrow(() -> new RuntimeException("Customer not found with id = " + id));
    }
    
    @DeleteMapping("/customer/{id}")
    public String deleteCustomer(@PathVariable Long id) {
        return customerRepository.findById(id)
                .map(customer -> {
                    customerRepository.delete(customer);
                    return "Delete Successfully!";
                }).orElseThrow(() -> new RuntimeException("Customer not found with id = " + id));
    }
}

-> With MediaType.APPLICATION_XML_VALUE, Spring uses a message converter to produces XML data.

Application configuration

– Open file application.properties, add configuration:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.generate-ddl=true
Run & Check Results

– Run SpringBoot application & start MySQL database.

-> Make post requests:

springboot-xml-restapi-mysql---post-request

springboot-xml-restapi-mysql---save-customers

-> Get customers:

springboot-xml-restapi-mysql---get-request-by-id

springboot-xml-restapi-mysql---get-all-customers

-> Put a customer:

springboot-xml-restapi-mysql---put-a-customer

springboot-xml-restapi-mysql---put-customers

– Delete a customer:

springboot-xml-restapi-mysql---delete-request

springboot-xml-restapi-mysql---delete-customers

Sourcecode

SpringBootXMLRestAPI

Leave a Reply

Your email address will not be published. Required fields are marked *