BackEnd - bounswe/bounswe2025group5 GitHub Wiki

Spring Framework Notes

Spring In Usage:

  • Spring Boot: 3.4.4
  • Maven
  • Java 21 JDK
  • MySQL Driver
  • Spring Web
  • Spring DATA JPA

Spring Beans

A Spring Bean is a Java object that is created and managed by the Spring Container. It is eligible for dependency injection.

  • Normally, the programmer takes care of object creation.
  • In Spring, the framework creates the object, injects its dependencies, and controls its lifecycle.

Bean:

An instance of a class managed by the Spring container.

Manual Creation:

MyService myService = new MyService();
@Component
public class MyService {
    // some logic
}

With Spring:

Inject its to the another class
@Autowired
private MyService myService;

Spring Container

  • Spring Container: Holds all beans, resolves dependencies between them, and controls their lifecycle.

@Component: Marks a class as bean @Autowired : Tells Spring to inject the required bean

Principles:

  • IoC(Inversion of Control):You give up control of creating and managing objects to a framework or container (like Spring), instead of doing it manually in your own code.

  • Dependency Inversion: design principle that Code should depend on abstractions, not concrete implementations

  • Dependency Injection: is a technique where an object gets its dependencies from outside, rather than creating them itself.

Example :

public class Car {
    private Engine engine = new Engine(); // tightly coupled
}

public class Car {
    private Engine engine;

    public Car(Engine engine) { // dependency is injected from outside
        this.engine = engine;
    }
}

Dependency Injection (DI) types:

  • Constructor injection
  • Field injection (@Autowired)
  • Setter injection

Mockito Testing:

Mockito is a Java library that helps you mock dependencies. In unit testing, we do not use real dependencies like databases or services. Instead, we simulate their behavior using mocks.

Mocks are like fake collaborators that behave exactly how program tells them.

It does:

  • Create mock objects of classes and interfaces.
  • Stub methods to return specific values.
  • Verify method interactions (e.g., whether a method was called, how many times, etc.).
  • Avoid depending on actual implementations (e.g., real databases, services, etc.).

Examples:

@Mock
private UserRepository userRepository;
(This tells Mockito to create a fake version of UserRepository.)

@InjectMocks
private AuthService authService;
(Tells Mockito to inject the mocked dependencies (userRepository, passwordEncoder, etc.) into the authService.)

@BeforeEach
void setup() {
    MockitoAnnotations.openMocks(this);
}
(Initializes all the mocks before each test case.)
  • when(...).thenReturn(...): tell the mock what to return when a method is called.
  • assertEquals(...): check if the output is what you expect.
  • Only the mocked versions of the database and services are used.

Spring Entity

Lombok reduce boilerplate code through compile-time code generation.

Boilerplate code:are sections of code that are repeated in multiple places with little to no variation.

  • @Data Getters, setters, toString(), equals(), hashCode()
  • @Getter Getters for all fields
  • @Setter Setters for all non-final fields
  • @ToString toString() method
  • @EqualsAndHashCode equals() and hashCode() methods
  • @NoArgsConstructor No-args constructor
  • @AllArgsConstructor Constructor with all fields

It reduces the code clutter, improves readability

  • OrphanRemoval: is an important cascade operation in JPA (Java Persistence API) that controls what happens to child entities when they're removed from a parent relationship
  • orphanRemoval is a JPA annotation attribute that:
    • When set to true, automatically deletes child entities when they're removed from their parent's collection
    • Only applies to @OneToMany and @OneToOne relationships

Use orphanRemoval=true when:

  • Child entities have no meaning without their parent (composition)
  • You want to automatically clean up "orphaned" children
  • You're modeling a true parent-child relationship where children shouldn't exist independently

Cloud Database Setup (Google Cloud SQL)

We will use Google Cloud Service to deploy our database. You can connect to it from your local environment.

Important Rules:

  • ⚠️ DO NOT CHANGE ANYTHING IN THE TABLES without permission
  • Everyone can use it for:
    • SELECT queries
    • Running applications locally
    • Examining the database structure

Connecting to Remote MySQL Server

MySQL Workbench Setup:

  1. Create a new connection by clicking the "+" button next to "MySQL Connections"
  2. Configure with these details:
    • Connection Name: wasteless
    • Hostname: [server IP provided to you]
    • Username: [username provided to you]
    • Password: [password provided to you] (store in vault)
  3. Click "Test Connection" to verify
  4. Once successful, save and close the configuration
  5. Open the connection to run queries

Spring Application Configuration:

Update your application.properties file:

spring.datasource.url=jdbc:mysql://<service_ip>/<database_name>?useSSL=false&serverTimezone=UTC
spring.datasource.username=<givenusername>
spring.datasource.password=<givenpassword>
⚠️ **GitHub.com Fallback** ⚠️