DZone
Integration Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Integration Zone > How to Develop RESTful Web Services Using MySQL and Spring Boot

How to Develop RESTful Web Services Using MySQL and Spring Boot

This article provides a 4-step tutorial on how to develop RESTful web services using MySQL and Spring Boot.

Shashank Bodkhe user avatar by
Shashank Bodkhe
·
Jul. 17, 18 · Integration Zone · Tutorial
Like (16)
Save
Tweet
54.89K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Boot is the fastest way to develop a spring application. Let's see how to develop such an application that uses MySQL Database to store the path of text files and image files and then using Spring MVC as an architectural pattern and Spring RESTful web services to fetch images and text. All this will be done using Spring Boot.

Step 1: Changes for Spring Boot

[1] On IDE like STS, Select NEW-> Project -> Spring Starter Project

Image title[2] We will get a screen as below (make names of project packages as desired, click next): 

Image title

[3] Select Spring Project Dependencies as MySQL, JPA, and Web. Click finish: 

3 Project Dependencies

[4] We will get project Structure as below: 

4 Project Structure

Here, we have obtained a Spring Boot application which uses features of

1. JPA: so that we can map java entities/Classes with MySQL Tables. 

2. MySQL: as we are using MySQL Database here.

3. Web: This dependency helps us to get restful endpoints to Fetch Images and Text on Web Browser 

Step 2: Changes According to Spring MVC Architecture 

 Next step is to make use of Spring MVC Architecture and design our Controller, Dao, and Service Layers. 

[1] Controller: ApplicationController.java

@RestController
@RequestMapping(value = "/application")
public class ApplicationController {

@Autowired
private ApplicationService applicationService;

@RequestMapping(value = "/get-image", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImagePath() throws IOException {
ResponseEntity<byte[]> responseEntity = applicationService.getImageURL();
return responseEntity;
}

@RequestMapping(value = "/get-text", method = RequestMethod.GET)
public ResponseEntity<byte[]> getTextPath() throws IOException {
ResponseEntity<byte[]> responseEntity = applicationService.getTextData();
return responseEntity;
}
}

[2] ApplicationDao.java: 

public interface ApplicationDao extends CrudRepository<RequestData,Integer> {
@Query(value = "SELECT * FROM resource_table WHERE File_id=?1", nativeQuery = true)
  RequestData findResource(Integer i);
}

[3] ApplicationService.java: (Note: I am using 1 as an argument to findResource as I will be creating only one DB entry, this logic can be changed according to the requirement, like findResourceByDate, etc.).

@Service
public class ApplicationService {

@Autowired
private ApplicationDao applicationDao;

public ResponseEntity<byte[]> getImageURL() throws IOException {

RequestData requestData = applicationDao.findResource(1);
String imagePath = requestData.getImages();

RandomAccessFile f = new RandomAccessFile(imagePath, "r");
byte[] b = new byte[(int) f.length()];
f.readFully(b);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);
}

public ResponseEntity<byte[]> getTextData() throws IOException {
RequestData requestData = applicationDao.findResource(1);
String s = requestData.getContents();

RandomAccessFile f = new RandomAccessFile(s, "r");
byte[] b = new byte[(int) f.length()];
f.readFully(b);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);
}

}

[4] The Java class that will be mapped with MySQL Table (name can be changed as per requirement):


@Entity
@Table(name = "resource_table")

public class RequestData {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "File_id")
private String id;

@Column(name = "Images_path")
private String images;

@Column(name = "Text_path")
private String Contents;

// getter-setters

}

Finally, the complete project structure should look like: 

5 Complete Structure

In the application.properties, make the following changes: 

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql = true

spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15

Step 3: MySQL Changes 

I am using MySQL for demonstration. DB may change as per requirement. Below is the sample Schema, Tables, and Insertion Data:

6 Database

I have a sample text file (with some text) and image file (Spring Boot logo) at local drive(E Drive). 

Step 4: Rendering Text and Image on Browser

[1]Start the spring boot application as below: 

7 Run Spring Boot

In the logs, you are going to see: 

2018-07-16 01:29:15.513  INFO 12640 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-16 01:29:15.584  INFO 12640 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-07-16 01:29:15.594  INFO 12640 --- [           main] com.boot.BootAngularRestApplication      : Started BootAngularRestApplication in 3.478 seconds (JVM running for 4.488)

Tomcat started on port 8080.

[2]  On web Browser, like Chrome, type in the below URL: 

[2.1] http://localhost:8080/application/get-image     

You will get the below output: 

8 image

[2.2] http://localhost:8080/application/get-text: 

Image title

Hope this helps, thanks! 

Spring Framework Spring Boot MySQL Web Service REST Web Protocols

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Understanding Cursors in Apache Pulsar
  • Happens-Before In Java Or How To Write a Thread-Safe Application
  • API Security Weekly: Issue 173
  • Here Is Why You Need a Message Broker

Comments

Integration Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo