Introduction
For this course we will be using MySQL as the database for permanent data storage. We will use Java Persistence API (JPA) as an Object Relation Map (ORM) to map Java classes to SQL tables and Java object instances to records. These instructions are also documented in the following βonline slides (βhttps://goo.gl /QFmEsk)β and βavailable online (βhttps://goo.gl/i6X4ssβ). This assignment assumes the successful completion of an βearlier assignmentβ.
Learning Objectives
By the end of this assignment you should be able to
- Create and configure a remote MySQL database on AWS
- Connect to a remote MySQL database with MySQL Workbench
- Integrate a Spring Boot Web project with a remote MySQL database
- Map Java POJOs to a relational schema using Java Persistence API
- Expose a data model through a Web service endpoint
Creating a Remote MySQL Instance on Heroku
This section describes creating a remote MySQL database instance running on Heroku. These steps assume you have successfully deployed a Spring Boot application on Heroku. If not, make sure to follow the instructions for setting up a remote account, remote application, and a development environment as described in βSettingup a Development Environment lecture. Once the environment is setup, create and deploy a Spring Boot application on Heroku as describe in Deploying Spring Boot Web Applications to Heroku.β Finally, add a remote MySQL database to the remote development environment as described in βAdding a Remote MySQL Database to a Spring Boot Web Application on Herokuβ. The general steps for setting up the environment on Heroku are listed below. Refer to the original documents for more details.
- Install βJDK 8β or later
- Install βApache Maven
- Install the βSpring Bootβ framework
- Install MySQL Workbencβ hβ or some other MySQL client
- Create an account on βHeroku
- Install the βHeroku CLI
- Create a simple Spring Boot Web application, e.g., spring init βdependencies=web myapp
Β
- Deploy the Spring Boot application to Heroku, e.g., heroku create
Β
- Add a MySQL remote database to the remote Spring Boot application on Heroku
- Connect your local MySQL Workbench to the remote MySQL on Heroku
Β
The connection string will contain the username, password, host and port. Make a note of this since youβll need it in later steps of this guide.
Creating a Remote MySQL Instance on AWS
This section describes creating a remote MySQL database instance running on AWS.
Β
- Login to the Amazon AWS console and expand All Servicesβ β.
- Under the βDatabaseβ section, select βRDSβ.
- In the βAmazon RDS landing page, select βLaunch or βGet Started Now to add a new RDS instance.
- In the βSelect engineβ screen, select βMySQLβ and then click βNextβ.
- In the βChoose use caseβ screen, select βDev/Test β MySQLβ and then click Nextβ β.
- In the βSpecify DB details screen, keep the default settings, and choose the following configuration and then click βNextβ. Use your own identifier, username, and password. The usernames, names, and identifiers shown in this document are based on a particular course, e.g., βcs5200β, semeter, e.g., βfall2018β, and your lastname, e.g., annunziato. Please use your particular values where applicable.β
Β
- DB instance class: βt2.micro
- DB instance identifier: βcs5200-fall2018-annunziato
- Master username: βjannunzi
- Master password: yourPa$$word123β
- Confirm password: βyourPa$$word123
Β
Make note of the actual values used above since they will be used in later steps.
Β
- In the βConfigure advanced settings screen, select Yesβ for the Publicβ accessibilityβ. Also, keep the default settings, but choose the name of the database, e.g., βcs5200_ fall2018_annunziatoβ. Note the use of underscores. This will be the name of the schema where tables and their records will be stored. Click on Launchβ DB Instance to continue. The database will take a few moments to be created after which you can navigate to it by clicking on βView DB Instance Detailsβ or clicking βInstancesβ on the left.
Β
- The details screen will be titled with the DB instance identifier chosen earlier, e.g., cs5200-fall2018-annunziatoβ. Scroll down to the βConnect Make a note of
the βEndpoint since it will be used later to connect remotely to the database. The endpoint is the name of the server machine where the database is running, e.g.,
Β
cs5200-fall2018-annunziato.cne500ro4imj.us-west-2.rds.amazonaws.com
Β
Also note the βPort where the server is listening for incoming connections, e.g., β3306.β If the βEndpoint is not yet available, wait a few more minutes while the database service is setup.
Β
- Note that the connection might not be publicly available by default as denoted by the configuration βPublicly accessible: Noβ. To make the connection publicly available, under the Security groupβ, click on the βInbound security group. In the security group screen, click the Inbound tab, and then the βEdit Under the βSource column, select βAnywhere from the dropdown, and click βSaveβ. Verify that the βPublicly accessibleβ setting is set to βYesβ.
Install, Configure, and Start MySQL Workbench
MySQL Workbench (Workbench) is a desktop application that provides a graphical user interface to easily interact with a MySQL database instance. Workbench will be used throughout to interact with MySQL running remotely on AWS or Heroku. To install Workbench, navigate to
Β
https://dev.mysql.com/downloads/workbench/
Β
and download Workbench for your particular operating system. Optionally signup and login, or scroll down a bit further and just start the download. After downloading, start the installation and accept all the defaults, and follow the steps below:
Β
- After installing, run the Workbench and create a new connection by clicking on the plus icon next to the βMySQL Connectionsβ
Β
- In the βSetup New Connection dialog, name your connection, e.g., cs5200-β connectionβ, and use the server name, port, master username, and master password noted earlier for the βHostnameβ, βPortβ, βUsernameβ, and βPasswordβ fields, and click βOkβ.
Β
- Click on the new connection to connect to the remote MySQL database and start interacting with it through Workbench.
Create a Simple, Sample Database
This section describes creating and interacting with a simple table with some sample data. From Workbench, create a new schema name based on the course you are enrolled in, e.g., βcs5200β.
Β
To create a new schema, click on the βNew Schema button (shown at right). In the new_schema screen, type the name of the schema in the βSchema Name field and click Applyβ. Verify that the following command will be executed and click βApply again and then βCloseβ (or βFinishβ).
Β
CREATE SCHEMA cs5200;
Β
Make the new schema the default schema by double clicking it or right clicking it, and then selecting βSet as default schemaβ.
Β
Create a table called βsample with a single field called βmessageβ. On Workbench, on the left, select the schema you created previously, and then click on the Newβ Table icon to create a new table (shown at right). Type βsample for the βNameβ. Under the Columnβ column, type βidβ, select checkboxes PK and AI, and press enter to create a primary key named βidβ.
Β
Under the βid field, type βmessageβ, select βVARCHAR(45) for the DatatypeβΒ Β β, and click ApplyβΒ Β Β Β Β Β Β Β Β β. Verify the following command will be executed and click βApplyβ again and then βCloseβ.
Β
CREATE TABLE cs5200.sample (Β Β id INT NOT NULL AUTO_INCREMENT,Β Β message VARCHAR(45) NULL,Β Β PRIMARY KEY (id));
Β
On the left expand the Tablesβ β, expand the βsample table, expand the Columnsβ β, and verify the following fields are present: idβ and messageβ β. Insert some sample data by right clicking the sample table, select βSend to SQL Editorβ, and then Insertβ Statementβ. A new SQL editor window opens with the following SQL tempalate statement
Β
| INSERT INTO cs5200.sample
(id, message) VALUES (<{id: }>, <{message: }>); |
Β
Replace the following placeholders with the corresponding content
Β
| Placeholder | Replace with |
| <{id: }> | 1 |
| <{message: }> | βHello Jose Annunziatoβ |
Β
Use YOUR NAME instead. To execute the SQL Insert command, click on the Executeβ button (shown on right). To verify that the content was saved, right click on the sampleβ table again and select βSelect Rows β Limit 1000β. A new SQL editor window appears with the following SQL statement
Β
SELECT * FROM cs5200.sample;
Β
Verify that the results are listed below the command window similar to the following
Β
| id | message |
| 1 | Hello Jose Annunziato |
Β
Replace the values in the Insertβ command to insert some more records. Use the following values:
Β
| id | message |
| 2 | SQL is great |
| 3 | Java is awesome |
Β
Insert the new records and verify the new records exist.
Integrate Spring Boot with MySQL
Start βSpring Tool Suite (STS) and open the project created in an βearlier assignmentβ. Open the file βapplication.properties under βsrc/main/resources and type the following content to configure the datasource JPA will use to connect to the database
Β
spring.datasource.url=jdbc:mysql://SERVER/SCHEMA spring.datasource.username=USERNAME spring.datasource.password=PASSWORD
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.datasource.testWhileIdle=true spring.datasource.validationQuery=SELECT 1
Β
where βSERVERβ, SCHEMAβ ,β USERNAMEβ ,β and βPASSWORD above, are the server name, master username, and master password noted earlier when setting up the aws server instance. Based on the values from earlier, the three lines would be
Β
spring.datasource.url=jdbc:mysql://βcs5200-fall2018-annunziato.cne500r o4imj.us-west-2.rds.amazonaws.comβ/βcs5200_fall2018_annunziato
spring.datasource.username=jannunzi spring.datasource.password=myPa$$word123
Β
Configure the project to download and install the MySQL Java connector library. Open the pom.xml file at the root of the project and type the following to download and install the Java MySQL library
Β
| <dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> |
Β
If you are using Java 9, youβll need to add the following βdependencies section:β
Β
| <dependency>
<groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> |
Β
If you are using Java 9, youβll need to add the following in the pluginsβ section:β
Β
| <plugin>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> |
Β
Configure a POJO to map to an SQL table and record instances. Open the HelloObjectβ .javaβ file you created in an βearlier assignmentβ and add the following content
Β
| import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;
Β @Entity(name=βhelloβ) public class HelloObject { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } } |
Β
The β@Entity annotation above maps the βHelloObject class to a table called βhelloβ. All the properties in the class are mapped to fields of the same name. The β@Id annotation configures the βid property as the primary key. The @GeneratedValueβ annotation configures the idβ property to be generated automatically by the database, e.g., AUTO_INCREMENTβ .β Spring Boot allows interacting with a database using the Java Persitence API (JPA) implemented through Springβs JpaRepositoryβ class. JPA allows interacting with a database saving and retrieving Java object instances, each representing records in a table in the database. To use JPA you need to create your own class that extends JpaRepository and configures the Java class and its primary key type. Create a βHelloRepository.javaβ interface with the following content
Β
package edu.neu.cs5200.controllers.hello;
Β
import org.springframework.data.jpa.repository.JpaRepository;
Β
public interface HelloRepository extends JpaRepository<HelloObject, Integer> { }
Β
Once the βJpaRepository has been declared, it can be used to save and retrieve records from the database. Add the following to the controller βHelloController.java created in an earlier assignmentβ:
Β
| import org.springframework.beans.factory.annotation.Autowired;
@RestController public class HelloController { Β @Autowired HelloRepository helloRepository; Β @RequestMapping(β/api/hello/insertβ) public HelloObject insertHelloObject() { HelloObject obj = new HelloObject(βHello Jose Annunziato!β); helloRepository.save(obj); return obj; } } |
Β
Replace Jose Annunziato with YOUR NAME. The above source creates a new instance of the
HelloObject with the βmessage property set to the constant literal βHelloβΒ Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Jose
Annunziato!β and then saves it to the database. In addition, letβs also create an endpoint that allows passing an arbitrary message as a parameter and then save it to the database. Add the following method to the βHelloController class:β
Β
| @RequestMapping(β/api/hello/insert/{msg}β)
public HelloObject insertMessage(@PathVariable(βmsgβ) String message) { HelloObject obj = new HelloObject(message); helloRepository.save(obj); return obj; } |
Β
The above code maps the URL pattern /api/hello/insert/{msg}β to the insertβ Message() method. The URL contains path variable {β msg},β a placeholder that can be any string. The actual string value is then mapped to method parameter messageβ using the @PathVariable annotation. Finally, letβs add a method to retrieve all the records from the database and return them as a βList of βHelloObject instances using the βfindAll() method. Add the following to method to the βHelloControllerβ class:
Β
| @RequestMapping(β/api/hello/select/allβ)
public List<HelloObject> selectAllHelloObjects() { List<HelloObject> hellos = (List<HelloObject>)helloRepository.findAll(); return hellos; } |
Β
The above code maps the URL pattern /api/hello/select/allβ to the selectAllHelloβ Objects() method. The method uses the helloRepository.findAll()β method to retrieve all records from the hello table and converts them to a βList of βHelloObject instances.
Β
Enable remote REST APIs on AWS by extending βSpringBootServletInitializer in your SpringBootApplication class you created in an βearlier assignmentβ, e.g., βCs5200Fall
2018AnnunziatoApplicationβ:
Β
| package edu.neu.cs5200;
Β import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class Cs5200Fall2018AnnunziatoApplication extends SpringBootServletInitializerβ { Β @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources( CS5200Fall2018AnnunziatoApplication.class); } |
| public static void main(String[] args) {
SpringApplication.run( Cs5200Fall2018AnnunziatoApplication.class, args); } } |
Β
Save all files and rebuild the project. Right click on the project and select βMaven and then Update Projectβ. From the command line, navigate to the project directory and build the project using maven
Β
mvn clean install
Β
To test your new Webservice end point, start the Tomcat server and point your browser to
Β
http://localhost:8080/api/hello/insert
Β
Verify the server responds with the following JSON:
Β
{
βidβ: 1,
βmessageβ: βHello Jose Annunziato!β
}
Β
Reload a couple of time and verify the βid increments everytime you reload. List all the records by pointing your browser to βhttp://localhost:8080/api/hello/select/allβ. Verify the server responds with the following JSON:
Β
| [
{ βidβ: 1, βmessageβ: βHello Jose Annunziato!β }, { βidβ: 2, βmessageβ: βHello Jose Annunziato!β }, { βidβ: 3, βmessageβ: βHello Jose Annunziato!β }, |
]
Β
Now try inserting some random messages, e.g., βJPA Rocksβ, βSpringβs the Bestβ, using the insert/{msg}β URL pattern. Point your browser to the following URLs:
Β
http://localhost:8080/api/hello/insert/JPA Rocks http://localhost:8080/api/hello/insert/Springβs the Best
Β
List all the records by pointing your browser to http://localhost:8080/api/hello/select/alβ l.β Verify the server responds with the following JSON:
Β
| [
{ βidβ: 1, βmessageβ: βHello Jose Annunziato!β }, { βidβ: 2, βmessageβ: βHello Jose Annunziato!β }, { βidβ: 3, βmessageβ: βHello Jose Annunziato!β }, { βidβ: 4, βmessageβ: βJPA Rocksβ }, { βidβ: 5, βmessageβ: βSpringβs the Bestβ }, ] |
Β
In Workbench, verify the data has been saving to the database by right clicking on the helloβ table on the left, and selecting βSelect Rows β Limit 1000β. A new SQL editor window appears with the following SQL statement
Β
SELECT * FROM cs5200.hello;
Β
Verify that the results are listed below the command window similar to the following:
Β
| id | message |
| 1 | Hello Jose Annunziato! |
| 2 | Hello Jose Annunziato! |
| 3 | Hello Jose Annunziato! |
| 4 | JPA Rocks |
| 5 | Springβs the Best |
Β
Where the messages should include YOUR NAME instead. Redeploy the war file to the remote Web application deployed on AWS and verify the links work there as well. The links should look similiar to the following:
Β
http://cs5200-fall2018-annunziato.us-west-2.elasticbeanstalk.com/api/hello/insert http://cs5200-fall2018-annunziato.us-west-2.elasticbeanstalk.com/api/hello/insert/Some parameterized message
http://cs5200-fall2018-annunziato.us-west-2.elasticbeanstalk.com/api/hello/select/all
Β
Note that when the application recompiles and/or redeploys, the tables are recreated and previous data is lost. This is fine for now while we are getting started in the early stages of development and we have not settled on a data model and the schema needs to reflect changes in the data model. When we settle on a data model, in later assignments, we will reconfigure JPA to not recreate the tables and loose our data.
Deliverables
As a deliverable add a section called βIntegrating Spring Boot with MySQLβ to your Submission.md file that contains three links to the Web service endpoints created in this assignment. The links should return JSON data similar in structure and content as verified throughout the assignment. The βSubmission.mdβ should look as follows:
Integrating Spring Boot with MySQL
Insert a parameterized hello message
Add, commit and push all the work completed under the Project-2β directory, to your course repository setup in an earlier assignment. Use the following message for your commit:
βIntegrating Spring Boot with MySQLββ.




