ECE366 - Lesson 5
Spring Boot and JPA
Instructor: Professor Hong
## What is the Spring Framework?
- Framework for providing comprehensive infrastructural support for developing Java Apps
- OOP (Object Oriented Programming) Best practices built in
- DRY (Don't Repeat Yourself) Principles
## What is Spring Boot?
- A tool that supports rapid development of web APIs
- Auto-configuration of Application Context
- Automatic Servlet Mappings
- Database support
- Automatic Controller Mappings
## Spring Initializr
- start.spring.io
- Project: Maven
- Language: Java
- Spring Boot: 3.4.3
- Group: com.chrishong.rps
- Artifact: rps
- Java 21
- Add spring web dependency
Download the zip file and put it in your workspace
## Update the pom.xml file
```
<?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>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.chrishong</groupId>
<artifactId>rps</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rps</name>
<description>RPS Game</description>
<properties>
<java.version>17</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-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>
com.chrishong.rps.RpsApplication
</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
- Add postgresql dependency
## Copy over JDBC libraries
- util - DataAccessObject, DataTransferObject
- DatabaseConnectionManager
- Player
- PlayerDAO
## Main
```
package com.chrishong.rps;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
@SpringBootApplication
@RestController
public class RpsApplication {
// Sample hello world API
@GetMapping("/helloClass")
public String helloClass() {
System.out.println("HELLO");
return "Hello Class";
}
/**
* Get all Players entities in the database.
*
* @return Player.
*/
@GetMapping("/getPlayerById/{id}")
public Player create(@PathVariable("id") long id) {
System.out.println(id);
DatabaseConnectionManager dcm = new DatabaseConnectionManager("localhost",
"rps", "postgres", "password");
Player player = new Player();
try {
Connection connection = dcm.getConnection();
PlayerDAO playerDAO = new PlayerDAO(connection);
player = playerDAO.findById(id);
System.out.println(player);
}
catch(SQLException e) {
e.printStackTrace();
}
return player;
}
public static void main(String[] args) {
System.out.println("Hello World");
SpringApplication.run(RpsApplication.class, args);
}
}
```
- Note we added ```RestController``` and ```GetMapping```
- ```GetMapping``` specifies what the API url maps to
## Testing with Postman
- Create a post request with the following url: ```http://localhost:8080/getPlayerById/1```
- Add a Body with the message desired: ```issac```
- Send the request
- You can also run this on chrome
## PostMapping
```
import com.fasterxml.jackson.databind.ObjectMapper;
@PostMapping("/createNewPlayer")
public Player createNewPlayer(@RequestBody String json) throws JsonProcessingException {
System.out.println(json);
ObjectMapper objectMapper = new ObjectMapper();
Map inputMap = objectMapper.readValue(json, Map.class);
DatabaseConnectionManager dcm = new DatabaseConnectionManager("localhost",
"rps", "postgres", "password");
Player player = new Player();
try {
Connection connection = dcm.getConnection();
PlayerDAO playerDAO = new PlayerDAO(connection);
player.setUserName(inputMap.get("userName"));
player.setPassword(inputMap.get("password"));
player = playerDAO.create(player);
System.out.println(player);
}
catch(SQLException e) {
e.printStackTrace();
}
return player;
}
```
- We use the jackson library to parse the json
## Docker Compose
```
services:
db:
image: postgres
volumes:
- $HOME/srv/postgres:/var/lib/postgresql/data
environment:
- POSTGRES_DB=postgres
- POSTGRES_PASSWORD=password
expose:
- 5432:5432
ports:
- 5432:5432
restart: always
app:
build: .
environment:
- POSTGRES_DB=postgres
- POSTGRES_PASSWORD=password
expose:
- 8080:8080
ports:
- 8080:8080
depends_on:
- db
```
## Dockerfile for Spring Boot
```
FROM maven:3.9.6-eclipse-temurin-21 AS build
ADD . /project
WORKDIR /project
RUN mvn -e package
FROM eclipse-temurin:latest
COPY --from=build /project/target/rps-0.0.1-SNAPSHOT.jar /app/rps.jar
ENTRYPOINT java -jar /app/rps.jar
```
## Common Traps
- Make sure you don't have another spring boot application running on the same port
- Rebuild your docker compose if you edited docker-compose.yaml or any Dockerfiles
- Make sure you use your docker compose services name for your database
## Java Persistence API (JPA)
- Standard Java EE (Jakarta EE) specification for ORM (Object–Relational Mapping)
- Allows you to map between objects and database tables
- Streamlines persistence to standard format
- Reduces JDBC code
- Focus on OOP
## resources/application.properties
```
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:postgresql://${POSTGRES_HOST}:5432/${POSTGRES_DB}
spring.datasource.username=postgres
spring.datasource.password=${POSTGRES_PASSWORD}
```
## Hard coded
```
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:postgresql://localhost:5432/rps
spring.datasource.username=postgres
spring.datasource.password=password
```
## pom.xml
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```
## Important Annotations
- ```@RestController``` - enables API endpoints
- ```@Entity``` - a row from the database
- ```@Table``` - the table name
- ```@Id``` - the ID of a table row
- ```@Column``` - a column of the table
- ```@GeneratedValue``` - strategies for primary key
## Code Organization for JPA
## Player Class
data/Player.java
```
package com.chrishong.rps.data;
import jakarta.persistence.*;
@Entity
@Table(name="PLAYER")
public class Player {
@Id
@Column(name="PLAYER_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long playerId;
@Column(name="USER_NAME")
private String userName;
@Column(name="PASSWORD")
private String password;
@Column(name="TOTAL_GAMES")
private int totalGames;
@Column(name="TOTAL_WINS")
private int totalWins;
@Column(name="TOTAL_LOSSES")
private int totalLosses;
public long getPlayerId() {
return playerId;
}
public void setPlayerId(long playerId) {
this.playerId = playerId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTotalGames() {
return totalGames;
}
public void setTotalGames(int totalGames) {
this.totalGames = totalGames;
}
public int getTotalWins() {
return totalWins;
}
public void setTotalWins(int totalWins) {
this.totalWins = totalWins;
}
public int getTotalLosses() {
return totalLosses;
}
public void setTotalLosses(int totalLosses) {
this.totalLosses = totalLosses;
}
@Override
public String toString() {
return "User{" +
"userId=" + playerId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", totalGames=" + totalGames +
", totalWin=" + totalWins +
", totalLoss=" + totalLosses +
'}';
}
}
```
## PlayerRepository Interface
data/PlayerRepository.java
```
package com.chrishong.rps.data;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PlayerRepository extends JpaRepository {
}
```
## PlayerService
business/PlayerService
```
package com.chrishong.rps.business;
import com.chrishong.rps.data.User;
import com.chrishong.rps.data.UserRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@Service
public class PlayerService {
private final PlayerRepository playerRepository;
public PlayerService(PlayerRepository playerRepository) {
this.playerRepository = playerRepository;
}
public List getPlayers(){
Iterable players = this.playerRepository.findAll();
List playerList = new ArrayList<>();
players.forEach(player->{playerList.add(player);});
return playerList;
}
}
```
## WebserviceController
webservice/WebserviceController.java
```
package com.chrishong.rps.webservice;
import com.chrishong.rps.business.UserService;
import com.chrishong.rps.data.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class WebserviceController {
private final PlayerService playerService;
public WebserviceController(PlayerService playerService) {
this.playerService = playerService;
}
@GetMapping("/players")
public List getPlayers(){
System.out.println("getPlayers");
return this.playerService.getPlayers();
}
@GetMapping("/testPlayer")
public String getTestPlayer() {
return "TEST PLAYER";
}
}
```
## Dockerfile
```
FROM maven:3.9.6-eclipse-temurin-21 AS build
ADD . /project
WORKDIR /project
RUN mvn -e -Dmaven.test.skip package
FROM eclipse-temurin:latest
COPY --from=build /project/target/rpsjpa-0.0.1-SNAPSHOT.jar /app/rps.jar
ENTRYPOINT java -jar /app/rps.jar
```
- Note, the ```-Dmaven.test.skip``` skips tests during the build
## Docker Compose
```
services:
db:
image: postgres
volumes:
- $HOME/srv/postgres:/var/lib/postgresql/data
environment:
- POSTGRES_DB=postgres
- POSTGRES_PASSWORD=password
expose:
- 5432:5432
ports:
- 5432:5432
restart: always
app:
build: .
environment:
- POSTGRES_HOST=db
- POSTGRES_DB=rps2
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
expose:
- 8080:8080
ports:
- 8080:8080
depends_on:
- db
```
- Don't forget to update the applications.properties file!