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](start.spring.io)
- Maven
- Java
- 3.2.2
- Group: com.chrishong.rps
- Artifact: rps
- Add spring boot 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>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</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 {
/**
* Get all Players entities in the database.
*
* @return Player.
*/
@GetMapping("/getPlayerById/{playerName}")
public Player create(@PathVariable("playerName") String playerName) {
System.out.println(playerName);
DatabaseConnectionManager dcm = new DatabaseConnectionManager("localhost",
"rps2", "postgres", "password");
Player player = new Player();
try {
Connection connection = dcm.getConnection();
PlayerDAO playerDAO = new PlayerDAO(connection);
player.setPlayerName(playerName);
player = playerDAO.findById(player);
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```
- 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",
"rps2", "postgres", "password");
Player player = new Player();
try {
Connection connection = dcm.getConnection();
PlayerDAO playerDAO = new PlayerDAO(connection);
player.setPlayerName(inputMap.get("playerName"));
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
## 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
## User Class
data/User.java
```
package com.chrishong.rps.data;
import jakarta.persistence.*;
@Entity
@Table(name="USERS")
public class User {
@Id
@Column(name="USER_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
@Column(name="USER_NAME")
private String userName;
@Column(name="PASSWORD")
private String password;
@Column(name="TOTAL_GAMES")
private int totalGames;
@Column(name="TOTAL_WIN")
private int totalWin;
@Column(name="TOTAL_LOSS")
private int totalLoss;
@Column(name="TOTAL_TIE")
private int totalTie;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
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 getTotalWin() {
return totalWin;
}
public void setTotalWin(int totalWin) {
this.totalWin = totalWin;
}
public int getTotalLoss() {
return totalLoss;
}
public void setTotalLoss(int totalLoss) {
this.totalLoss = totalLoss;
}
public int getTotalTie() {
return totalTie;
}
public void setTotalTie(int totalTie) {
this.totalTie = totalTie;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", totalGames=" + totalGames +
", totalWin=" + totalWin +
", totalLoss=" + totalLoss +
", totalTie=" + totalTie +
'}';
}
}
```
## UserRepository Interface
data/UserRepository.java
```
package com.chrishong.rps.data;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
## UserService
business/UserService
```
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 UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List getUsers(){
Iterable users = this.userRepository.findAll();
List userList = new ArrayList<>();
users.forEach(user->{userList.add(user);});
return userList;
}
}
```
## 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 UserService userService;
public WebserviceController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users")
public List getUsers(){
System.out.println("getUsers");
return this.userService.getUsers();
}
@GetMapping("/testuser")
public String getTestUser() {
return "TEST USERS";
}
}
```