PCF - Spring Boot + MySQL Example (2024)
As seen in previous tutorial, we learned how to develop and deploy Spring Boot application to PCF.
Now lets move ahead and learn step by step how develop and deploy Spring Boot JPA with MySql to Pivotal Cloud Foundry(PCF).
Note : The full source code for Spring Boot MySql PCF example can be downloaded at the end of this article.
To test this application at local will use MySql, however to test with PCF, will see how to create MYSQL service and bind.
- Project will look as given below
- Let's Create Spring Boot Project from Spring Initializer site https://start.spring.io/
Provide all details as given below and Generate Project.
Import the generated spring boot project in Eclipse/STS/Intellj IDE by using "Import Existing Maven Project". - Generated Spring Boot project will create below pom.xml with MYSQL and JPA dependencies for persistency.
- Provide datasource properties in application.properties
Note: Provide correct dialect value, for MYSQL 8 at local, i have given MySQL8Dialect. - Create manifest.yml, you can see we have provided service name as mysqldb, which is MYSql database created in PCF.
- Let's create Employee Model class
-
Create JPA Repository (Data Layer), to access the information stored in the database using JPA. We have used JpaRepository, with this feature no need to write extra logic to retrieve data from database.
JPA provides Repositories like JpaRepository and CrudRepository.
CrudRepository mainly provides CRUD functions while JpaRepository provide some JPA related methods such as flushing the persistent context, deleting records in a batch. - Create Service Layer and its Implementation to expose the services.
- Now, it's time to call this service from Controler.
- To test this application, we have added employee record in database as given below from Main Application
- Now build and run this application at local to test. At local, this application will connect to local MYSQL. Use localhost to connect to application.
Once tested at local, will try to test on Cloud Foundry. Follow below steps to create MySQL service and to deploy on Pivotal Cloud Foundry. - Create MySQL service on Pivotal Cloud Foundry
- Login to PCF Pivotal Cloud Foundry
- Click on Marketplace
- Search for MySql, click on clearDB MYSQL
- Click on Select This Plan button
- Give service name, same as provided in manifest.yml file and click on Create button
-
Deploy your application by using cf push command from command prompt at path where manifest.yml resides. Click here, to know more in details to login to Cloud Foundry from command prompt.
- Once application deployment is done using push command to Cloud Foundry, go to Pivotal Cloud Foundry Web.
- Click on Organization-> Development, you can see your Spring Boot App deployed to PCF.
- Finally to test the application, use link provided under Route column.
Note: Route is getting generated randomly, because we have declaredrandom-route: true
property in manifest.yml. If you want specific fixed route to be generated every time, declare application namename: springboot-mysql-example
instead in manifest.yml.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext.emp.task</groupId>
<artifactId>Emp-Task</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Emp-Task</name>
<description>Sample project for Spring Boot MySql PCF</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/notesdb?createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.platform=mysql
spring.datasource.initialization-mode=always
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = create-drop
applications:
- name: Emp-Task
memory: 768M
instances: 1
path: target\Emp-Task-0.0.1-SNAPSHOT.jar
random-route: true
services:
- mysqldb
buildpacks:
- https://github.com/cloudfoundry/java-buildpack.git
package com.techgeeknext.emp.task.EmpTask.model;
import javax.persistence.*;
import javax.validation.constraints.Size;
import java.io.Serializable;
@Entity
@Table(name="employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name="emp_id")
private Long id;
@Size(max = 1000)
@Column(name="emp_name")
private String empName;
public Employee(String name) {
this.empName = name;
}
public Employee() {
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
package com.techgeeknext.emp.task.EmpTask.repository;
import com.techgeeknext.emp.task.EmpTask.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
package com.techgeeknext.emp.task.EmpTask.service;
import com.techgeeknext.emp.task.EmpTask.model.Employee;
import java.util.List;
public interface EmployeeService {
public List<Employee> getAllEmployees();
}
Implementation Class
package com.techgeeknext.emp.task.EmpTask.service;
import com.techgeeknext.emp.task.EmpTask.model.Employee;
import com.techgeeknext.emp.task.EmpTask.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
/**
* Get all employees
* @return object
*/
@Override
public List<Employee> getAllEmployees() {
return (List<Employee>) employeeRepository.findAll();
}
}
package com.techgeeknext.emp.task.EmpTask.controller;
import com.techgeeknext.emp.task.EmpTask.model.Employee;
import com.techgeeknext.emp.task.EmpTask.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@RequestMapping(value = "/get/employees", method = RequestMethod.GET)
public String getEmployees() {
final List<Employee> employees = employeeService.getAllEmployees();
StringBuilder empDetails = new StringBuilder();
if(employees !=null){
for (Employee employee:employees) {
empDetails.append(employee.getEmpName());
empDetails.append("\n");
}
}
return empDetails.toString();
}
}
package com.techgeeknext.emp.task.EmpTask;
import com.techgeeknext.emp.task.EmpTask.model.Employee;
import com.techgeeknext.emp.task.EmpTask.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmpTaskApplication implements CommandLineRunner {
@Autowired
private EmployeeRepository employeeRepository;
public static void main(String[] args) {
SpringApplication.run(EmpTaskApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
Employee employee = new Employee();
employee.setEmpName("TechGeekNext Employee 1");
employeeRepository.save(employee);
}
}
Download Source Code
The full source code for this article can be found on below.Download it here - springboot-mysql-pcf-example