Skip to content

simulations v0.4

Albert edited this page Apr 25, 2024 · 27 revisions

Project Overview

In this lab we are going to:

  • Focus on API Rest and H2 JPA
  • Delete web features
  • Work on @OneToMany with 2 @Entities
  • Define DDD

Project structure

image

POM

pom.xml

  • new dependencies: JPA and H2
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Model

JPA @OneToMany bidirectional

Entities

Annotations:

  • @OneToMany: Establishes one-to-many relationship. Example: Player can have multiple Simulation. Used in JPA/Hibernate. Annotation: @OneToMany(mappedBy = "Player").mappedBy: Indicates the field on the inverse side of a bidirectional relationship. Specifies the field in the owning side that maps the relationship. Example: In a bidirectional OneToMany, mappedBy points to the field in the ManyToOne side.
  • @ManyToOne: Specifies many-to-one relationship. Multiple instances are associated with one instance of another entity. Example: Many simulation belong to one player.
  • @JoinColumn: Customizes join column. Example: Specifies foreign key column in @ManyToOne or @OneToOne relationships. Annotation: @JoinColumn(name = "PLAYER_FK").
  • @JsonIgnore: Excludes field from serialization/deserialization. Example: Hides sensitive or irrelevant data in JSON responses. Annotation: @JsonIgnore.

Player

image

package com.example.demo.model;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;


@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Player {

    @Id
    private String id;
    private String player;
    private int age;
    private boolean active;

    @OneToMany(mappedBy = "player", cascade = CascadeType.ALL)
    private List<Simulation> simulations = new ArrayList<>();

    public void addSimulation(Simulation simulation) {
        this.getSimulations().add(simulation);
        //if (simulation.getId() != null) simulation.getId().getSimulations().remove(simulation);
        simulation.setPlayer(this);
    }
}

Simulation

image

package com.example.demo.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor @AllArgsConstructor
@Entity
public class Simulation {

    @Id
    private String id;
    private String createdAt;
    private int timeElapsed;
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="PLAYER_FK")
    private Player player;


}

DataBase

H2 in-memory configuration

datasource

application.properties

server.port=8089

#H2 DATASOURCE
spring.datasource.url=jdbc:h2:mem:0f74afd0-eefb-4b37-af9f-64249cb2ffa2
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

#DDL
spring.jpa.hibernate.ddl-auto=create-drop

CRUD Repository

image

Populate DB with fake data

Fake data for simulation object

image

Command line runner

Runner

RunnerFillingDB.java

Service to Populate DB

Player & Simulation

We need to assign player to simulation related to @ManyToOne relationship (the many side). When JPA writes objects to DB table/columns, there must be the id from player as Foreign Key in simulation table.

simulation table must have a column with the Foreign Key from player: PLAYER_FK

In Java player is an object. In DB, simulation table, player is an id (PLAYER_FK), player id as a Foreign Key

public void populate() {

        // locale in english
        Faker faker = new Faker(new Locale("en-GB"));
        List<Simulation> simulations;
        // ref variable creation UUID
        String uniqueID;

        for (int i = 0; i <10 ; i++ ){

            uniqueID = UUID.randomUUID().toString();
            Player player =  new Player();
            player.setId(uniqueID);
            player.setActive(true);
            player.setPlayer( faker.artist().name());
            player.setAge(faker.number().numberBetween(10, 100));

            simulations = simulationService.createFakeSimulations();

            for (int j = 0; j <10 ; j++ ) {
                player.addSimulation(simulations.get(j));
            }
            playerRepository.save(player);

        }
}

Controller

Rest Controller

image

Output

H2 console

http://localhost:8089/h2-console/

SELECT * FROM PLAYER

image

SELECT * FROM SIMULATION

image

Postman API Rest

http://localhost:8089/api/v1/player/players

image