In this Spring Boot tutorial, I will show you a Restful Web service example in that Spring REST Controller can receive/consume XML Request Body and return XML Response instead of JSON. We also use Spring Data JPA to interact with database (MySQL/PostgreSQL).
More Practice:
– Documentation: Spring Boot + Swagger 3 example (with OpenAPI 3)
– Caching: Spring Boot Redis Cache example
– Spring Boot Thymeleaf CRUD example
– Spring Boot, Spring Data JPA – Building Rest CRUD API example
– Spring Boot + GraphQL + MySQL example
Associations:
– Spring Boot One To One example with JPA, Hibernate
– Spring Boot One To Many example with JPA, Hibernate
– Spring Boot Many to Many example with JPA, Hibernate
Deployment:
– Deploy Spring Boot App on AWS – Elastic Beanstalk
– Docker Compose: Spring Boot and MySQL example
Contents
- Spring Boot XML REST Service
- Return XML Responses
- Overview of Spring Boot Rest XML example
- Technology
- Project Structure
- Create & Setup Spring Boot project
- Configure Spring Datasource, JPA, Hibernate
- Define Data Model
- Create Repository Interface
- Configure Content Negotiation for XML Type
- Create Spring Rest APIs Controller
- Run & Test
- Conclusion
- Further Reading
- Source Code
Spring Boot XML REST Service
There are two ways to render XML responses:
- Using Jackson XML extension (
jackson-dataformat-xml
) to render XML responses is easy, just add the following dependency:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
So XML can be rendered by annotating @XmlRootElement
at the data model lass:
@XmlRootElement
public class Tutorial {
private String title;
// .. getters and setters
}
In this example, we’re gonna use the first way.
Return XML Responses
You can tell Controller which methods should return XML Responses by using MediaType.APPLICATION_XML_VALUE
as produces
value of @RequestMapping
annotation.
@RequestMapping(value="/tutorials/{id}", produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") long id) {
// ...
}
In case you want to make all Controller methods return XML Reponses, you don’t have to mark each methods with produces=MediaType.APPLICATION_XML_VALUE
. Just implement content negotiation by implementing WebMvcConfigurer
and override configureContentNegotiation()
.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_XML);
}
}
Overview of Spring Boot Rest XML example
We will build a Restful Web service that provides CRUD API for a Tutorial application in that:
- Each Tutorial has id, title, description, published status.
- Apis help to create, retrieve, update, delete Tutorials.
- Apis also support custom finder methods such as find by published status or by title.
- XML is the Content Type of HTTP Requests and Responses.
Here are the APIs:
Methods | Urls | Actions |
---|---|---|
POST | /api/tutorials | create new Tutorial |
GET | /api/tutorials | retrieve all Tutorials |
GET | /api/tutorials/:id | retrieve a Tutorial by :id |
PUT | /api/tutorials/:id | update a Tutorial by :id |
DELETE | /api/tutorials/:id | delete a Tutorial by :id |
DELETE | /api/tutorials | delete all Tutorials |
GET | /api/tutorials/published | find all published Tutorials |
GET | /api/tutorials?title=[keyword] | find all Tutorials which title contains keyword |
– We make CRUD operations & finder methods with Spring Data JPA’s JpaRepository
.
– The database could be PostgreSQL or MySQL depending on the way we configure project dependency & datasource.
Technology
- Java 8
- Spring Boot 2.2.1 (with Spring Web MVC, Spring Data JPA)
- PostgreSQL/MySQL
- Maven 3.6.1
- Jackson Dataformat XML 2.10.1
Project Structure
– WebConfig
implements WebMvcConfigurer. This is where we set the default content type.
– Tutorial
data model class corresponds to entity and table tutorials.
– TutorialRepository
is an interface that extends JpaRepository for CRUD methods and custom finder methods. It will be autowired in TutorialController
.
– TutorialController
is a RestController which has request mapping methods for RESTful requests such as: getAllTutorials, createTutorial, updateTutorial, deleteTutorial, findByPublished…
– Configuration for Spring Datasource, JPA & Hibernate in application.properties.
– pom.xml contains dependencies for Spring Boot, ackson Dataformat XML & MySQL/PostgreSQL.
Create & Setup Spring Boot project
Use Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project.
Then open pom.xml and add these dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
We also need to add one more dependency.
– If you want to use MySQL:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
– or PostgreSQL:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Configure Spring Datasource, JPA, Hibernate
Under src/main/resources folder, open application.properties and write these lines.
– For MySQL:
spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
– For PostgreSQL:
spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= postgres
spring.datasource.password= 123
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
spring.datasource.username
&spring.datasource.password
properties are the same as your database installation.- Spring Boot uses Hibernate for JPA implementation, we configure
MySQL5InnoDBDialect
for MySQL orPostgreSQLDialect
for PostgreSQL spring.jpa.hibernate.ddl-auto
is used for database initialization. We set the value toupdate
value so that a table will be created in the database automatically corresponding to defined data model. Any change to the model will also trigger an update to the table. For production, this property should bevalidate
.
Define Data Model
Our Data model is Tutorial with four fields: id, title, description, published.
In model package, we define Tutorial
class.
model/Tutorial.java
package com.bezkoder.spring.datajpa.xml.model;
import javax.persistence.*;
@Entity
@Table(name = "tutorials")
public class Tutorial {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "isPublished")
private boolean published;
public Tutorial() {
}
public Tutorial(String title, String description, boolean published) {
this.title = title;
this.description = description;
this.published = published;
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isPublished() {
return published;
}
public void setPublished(boolean isPublished) {
this.published = isPublished;
}
@Override
public String toString() {
return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
}
}
– @Entity
annotation indicates that the class is a persistent Java class.
– @Table
annotation provides the table that maps this entity.
– @Id
annotation is for the primary key.
– @GeneratedValue
annotation is used to define generation strategy for the primary key. GenerationType.AUTO
means Auto Increment field.
– @Column
annotation is used to define the column in database that maps annotated field.
Create Repository Interface
Let’s create a repository to interact with Tutorials from the database.
In repository package, create TutorialRepository
interface that extends JpaRepository
.
repository/TutorialRepository.java
package com.bezkoder.spring.datajpa.xml.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.bezkoder.spring.datajpa.xml.model.Tutorial;
public interface TutorialRepository extends JpaRepository<Tutorial, Long> {
List<Tutorial> findByPublished(boolean published);
List<Tutorial> findByTitleContaining(String title);
}
Now we can use JpaRepository’s methods: save()
, findOne()
, findById()
, findAll()
, count()
, delete()
, deleteById()
… without implementing these methods.
We also define custom finder methods:
– findByPublished()
: returns all Tutorials with published
having value as input published
.
– findByTitleContaining()
: returns all Tutorials which title contains input title
.
The implementation is plugged in by Spring Data JPA automatically.
More Derived queries at:
JPA Repository query example in Spring Boot
Custom query with @Query
annotation:
Spring JPA @Query example: Custom query in Spring Boot
You can modify this Repository:
– to work with Pagination, the instruction can be found at:
Spring Boot Pagination & Filter example | Spring JPA, Pageable
– or to sort/order by multiple fields with the tutorial:
Spring Data JPA Sort/Order by multiple Columns | Spring Boot
You also find way to write Unit Test for this JPA Repository at:
Spring Boot Unit Test for JPA Repository with @DataJpaTest
Configure Content Negotiation for XML Type
Now we’re gonna implement content negotiation in our Spring Boot project.
config/WebConfig.java
package com.bezkoder.spring.datajpa.xml.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_XML);
}
}
Create Spring Rest APIs Controller
Finally, we create a controller that provides APIs for creating, retrieving, updating, deleting and finding Tutorials.
controller/TutorialController.java
package com.bezkoder.spring.datajpa.xml.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.bezkoder.spring.datajpa.xml.model.Tutorial;
import com.bezkoder.spring.datajpa.xml.repository.TutorialRepository;
@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class TutorialController {
@Autowired
TutorialRepository tutorialRepository;
@GetMapping("/tutorials")
public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
try {
List<Tutorial> tutorials = new ArrayList<Tutorial>();
if (title == null)
tutorialRepository.findAll().forEach(tutorials::add);
else
tutorialRepository.findByTitleContaining(title).forEach(tutorials::add);
if (tutorials.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(tutorials, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/tutorials/{id}")
public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") long id) {
Optional<Tutorial> tutorialData = tutorialRepository.findById(id);
if (tutorialData.isPresent()) {
return new ResponseEntity<>(tutorialData.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping("/tutorials")
public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
try {
Tutorial _tutorial = tutorialRepository.save(new Tutorial(tutorial.getTitle(), tutorial.getDescription(), false));
return new ResponseEntity<>(_tutorial, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.EXPECTATION_FAILED);
}
}
@PutMapping("/tutorials/{id}")
public ResponseEntity<Tutorial> updateTutorial(@PathVariable("id") long id, @RequestBody Tutorial tutorial) {
Optional<Tutorial> tutorialData = tutorialRepository.findById(id);
if (tutorialData.isPresent()) {
Tutorial _tutorial = tutorialData.get();
_tutorial.setTitle(tutorial.getTitle());
_tutorial.setDescription(tutorial.getDescription());
_tutorial.setPublished(tutorial.isPublished());
return new ResponseEntity<>(tutorialRepository.save(_tutorial), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/tutorials/{id}")
public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") long id) {
try {
tutorialRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
}
@DeleteMapping("/tutorials")
public ResponseEntity<HttpStatus> deleteAllTutorials() {
try {
tutorialRepository.deleteAll();
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
}
@GetMapping("/tutorials/published")
public ResponseEntity<List<Tutorial>> findByPublished() {
try {
List<Tutorial> tutorials = tutorialRepository.findByPublished(true);
if (tutorials.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(tutorials, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
}
}
– @CrossOrigin
is for configuring allowed origins.
– @RestController
annotation is used to define a controller and to indicate that the return value of the methods should be be bound to the web response body.
– @RequestMapping("/api")
declares that all Apis’ url in the controller will start with /api
.
– We use @Autowired
to inject TutorialRepository
bean to local variable.
Run & Test
Run Spring Boot application with command: mvn spring-boot:run
.
tutorials table will be automatically generated in Database.
If you check MySQL for example, you can see things like this:
mysql> describe tutorials;
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| id | bigint(20) | NO | PRI | NULL | |
| description | varchar(255) | YES | | NULL | |
| is_published | bit(1) | YES | | NULL | |
| title | varchar(255) | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
Create Tutorials:
mysql> select * from tutorials;
+----+-----------------------+--------------+--------+
| id | description | is_published | title |
+----+-----------------------+--------------+--------+
| 1 | Tut#1 Description | 0 | Tut #1 |
| 2 | Tut#2 Description | 0 | Tut #2 |
| 3 | Tut#3 Description | 0 | Tut #3 |
| 4 | Description for Tut#4 | 0 | Tut #4 |
| 5 | Description for Tut#5 | 0 | Tut #5 |
+----+-----------------------+--------------+--------+
Get all Tutorials:
Get a Tutorial by Id:
Update some Tutorials:
mysql> select * from tutorials;
+----+-----------------------+--------------+---------------------+
| id | description | is_published | title |
+----+-----------------------+--------------+---------------------+
| 1 | Tut#1 Desc | 0 | bezkoder.com Tut #1 |
| 2 | Tut#2 Description | 0 | Tut #2 |
| 3 | Tut#3 Desc | 1 | bezkoder.com Tut #3 |
| 4 | Description for Tut#4 | 0 | Tut #4 |
| 5 | Tut#5 Desc | 1 | bezkoder.com Tut #5 |
+----+-----------------------+--------------+---------------------+
Find all published Tutorials:
Find all Tutorials which title contains ‘zkoder’:
Delete a Tutorial:
mysql> select * from tutorials;
+----+-------------------+--------------+---------------------+
| id | description | is_published | title |
+----+-------------------+--------------+---------------------+
| 1 | Tut#1 Desc | 0 | bezkoder.com Tut #1 |
| 2 | Tut#2 Description | 0 | Tut #2 |
| 3 | Tut#3 Desc | 1 | bezkoder.com Tut #3 |
| 5 | Tut#5 Desc | 1 | bezkoder.com Tut #5 |
+----+-------------------+--------------+---------------------+
Delete all Tutorials with API: DELETE http://localhost:8080/api/tutorials/
mysql> select * from tutorials;
Empty set (0.00 sec)
Conclusion
Today we’ve built a Spring Boot Rest XML example using Jackson XML extension to render XML and Spring Data JPA to interact with MySQL/PostgreSQL. You’ve known way to consume XML in Request Body and return XML Response.
If you want to learn more about Spring Boot Webservice that work with JSON data in Requests and Responses, please visit:
Spring Boot, Spring Data JPA – Building Rest CRUD API example
Custom query with @Query
annotation:
Spring JPA @Query example: Custom query in Spring Boot
You can modify this Repository:
– to work with Pagination, the instruction can be found at:
Spring Boot Pagination & Filter example | Spring JPA, Pageable
– or to sort/order by multiple fields with the tutorial:
Spring Data JPA Sort/Order by multiple Columns | Spring Boot
You also find way to write Unit Test for this JPA Repository at:
Spring Boot Unit Test for JPA Repository with @DataJpaTest
Or Documentation: Spring Boot + Swagger 3 example (with OpenAPI 3)
Happy learning! See you again.
Further Reading
- https://github.com/FasterXML/jackson-dataformat-xml
- Secure Spring Boot App with Spring Security & JWT Authentication
- Spring Data JPA Reference Documentation
Associations:
– Spring Boot One To One example with JPA, Hibernate
– Spring Boot One To Many example with JPA, Hibernate
– Spring Boot Many to Many example with JPA, Hibernate
Deployment:
– Deploy Spring Boot App on AWS – Elastic Beanstalk
– Docker Compose: Spring Boot and MySQL example
Source Code
You can find the complete source code for this tutorial on Github.
More Derived queries at:
JPA Repository query example in Spring Boot
Caching: Spring Boot Redis Cache example
very good, how do a client ???
Thanks for complete tutorial and working code.
I ᴡant to to thank you for this good tutorial!!