…. Java Spring Boot Grundlagen

Java Spring Boot simplified
Java Spring Boot components and layers

When a Java Spring Boot application is deployed on a server and the @SpringBootApplication class is active/executed, the application initializes and starts „listening“ for HTTP requests. When an HTTP request is received that matches a specific endpoint defined in a controller, the corresponding service or logic associated with that endpoint is executed.

What is Java Spring Boot?

Java Spring Boot is a framework designed to simplify the process of building and deploying Java-based applications. It is built on top of the Spring Framework, which is known for its comprehensive programming and configuration model. Spring Boot’s main goal is to reduce the complexity of configuration and setup, making it easier for developers to create production-ready applications quickly. By providing built-in support for various features, such as embedded web servers and auto-configuration, Spring Boot allows developers to focus more on the application’s business logic rather than the infrastructure. It is particularly well-suited for building microservices and web applications, as it streamlines the development process and promotes best practices for building scalable and maintainable systems.

How to set up Java Spring in IntelliJ IDEA Community Edition?

Go to Spring Initializr and set up the project. We are using Java (as you can assume from the title 🙂 ). Klick on Generate and you should automatically download a zip, which have your Spring project. Since all good things are free.. and we do not want to pay, we use the community edition of IntelliJ.

Open the project in IntelliJ. After downloading the zip, unzip it and open in IntelliJ. You can find the folder, which you have to open by simply noticing the black quadrat on the folder icon.

Two very important files should be set before starting writing any code: pom.xml and the application.properties files.

In a Java Spring Boot project, the pom.xml file manages project dependencies and build configurations, while the application.properties file stores application-specific settings such as configuration values, database connections, and logging preferences.

POM.xml

In a Java Spring Boot project, the pom.xml (Project Object Model) file is used for managing project dependencies, build configurations, and plugin settings. It is an essential part of the Maven build system, which is commonly used in Spring Boot applications. The pom.xml file defines the dependencies (like libraries or frameworks) that the project needs, the versions of those dependencies, and the build lifecycle (such as compiling, packaging, and deploying the application). It also handles configuration for plugins that automate tasks such as testing, code quality checks, and generating project reports. The pom.xml file simplifies project management by automating dependency resolution and build processes.

Example of the content of pom.xml with spring 4.3.1 is:

<?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.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>advquerying</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>advquerying</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

After you set up your pom file. Save it. You should be able to see small refresh icon in IntelliJ. After clicking it your External livraries folder should gain the additional libraries, which you need to continue.

application.properties

The application.properties file in a Java Spring Boot project is used to configure application-specific settings, such as database connections, server ports, logging levels, and other properties. It allows developers to externalize configuration values, making the application more flexible and easier to manage across different environments (e.g., development, testing, production). By modifying this file, developers can fine-tune application behavior without changing the code itself.

#Data Source Properties
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
# spring.datasource.url=jdbc:mysql://[host]:[port]/[dbname]?[options]
spring.datasource.url=jdbc:mysql://localhost:3306/MyDBName?useSSL=false&createDatabaseIfNotExist=true
spring.datasource.username=[YourUsername]
spring.datasource.password=[YourPassword]

#JPA Properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.format_sql = TRUE
spring.jpa.hibernate.ddl-auto = update
spring.jpa.open-in-view=false

###Logging Levels
# Disable the default loggers
logging.level.org = WARN
logging.level.blog = WARN

#Show SQL executed with parameter bindings
logging.level.org.hibernate.SQL = DEBUG
logging.level.org.hibernate.type.descriptor = TRACE

The file, which is starting the application in this example is DemoApplication. After setting the pom and the application.properties file you can check whether everything was successful simply by starting the application:

Entities

In Java Spring Boot, entities are a key concept in the persistence layer and typically represent the data model of your application. They map to tables in a database and are used to interact with the database in an object-oriented manner. Entities are part of the Java Persistence API (JPA), which Spring Boot often integrates using Hibernate as the default implementation.

Key Annotations

Here are some common annotations used in entities:

  • @Entity: Marks the class as a JPA entity.
  • @Table: (Optional) Used to specify the table name and schema if it differs from the class name.
  • @Id: Defines the primary key of the entity.
  • @GeneratedValue: Specifies the strategy for primary key generation.
  • @Column: Customizes the mapping of a field to a column.
  • @ManyToOne, @OneToMany, @OneToOne, @ManyToMany: Define relationships between entities.

The @MappedSuperclass annotation in Java Spring Boot is used in the context of JPA inheritance to define a common base class for entities that share mappings but are not themselves entities. It allows you to centralize common fields and mappings across multiple entity classes without having a dedicated table for the base class in the database.

Examples of Entities in Java Spring Boot

The following sections provide the code for the specified tables and their relationships:

ER Diagram
ER Diagram

BaseEntityClass

package com.example.demo.entities;

import jakarta.persistence.*;

@MappedSuperclass
public abstract class BaseEntityClass {

    private Long id;

    protected BaseEntityClass() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

PizzaaSize

package com.example.demo.entities;

public enum PizzaaSize {
    SMALL, MEDIUM, LARGE;
}

Pizzaa

package com.example.demo.entities;

import jakarta.persistence.*;

import java.math.BigDecimal;
import java.util.Set;

@Entity
@Table(name = "Pizzaa")
public class Pizzaa extends BaseEntityClass{

    private String PizzaName;
    private BigDecimal price;
    private PizzaaSize size;
    private Set<Toppings> toppings;

    public Pizzaa() {
    }

    @Column(name = "PizzaName")
    public String getPizzaName() {
        return this.PizzaName;
    }

    public void setPizzaName(String PizzaName) {
        this.PizzaName = PizzaName;
    }

    @Column(name = "price")
    public BigDecimal getPrice() {
        return this.price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    @Enumerated(EnumType.ORDINAL)
    @Column(name = "size")
    public PizzaaSize getPizzaaSize() {
        return this.size;
    }

    public void setPizzaaSize(PizzaaSize size) {
        this.size = size;
    }

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "pizzaa_toppings",
            joinColumns = @JoinColumn(name = "pizzaa_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "topping_id", referencedColumnName = "id"))
    public Set<Toppings> getToppings() {
        return this.toppings;
    }

    public void setToppings(Set<Toppings> toppings) {
        this.toppings = toppings;
    }

}

Toppings

package com.example.demo.entities;

import jakarta.persistence.*;

import java.math.BigDecimal;
import java.util.Set;

@Entity
@Table(name = "Toppings")
public class Toppings extends BaseEntityClass{

    private String name;
    private BigDecimal price;
    private Set<Pizzaa> pizzaas;

    public Toppings() {
    }

    @Column(name = "name")
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "price")
    public BigDecimal getPrice() {
        return this.price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    @ManyToMany(mappedBy = "toppings",
            fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    public Set<Pizzaa> getPizzaas() {
        return this.pizzaas;
    }

    public void setPizzaas(Set<Pizzaa> pizzaas) {
        this.pizzaas = pizzaas;
    }

}

Once you set the application settings correctly and the entities. You can create the database simply by running the application. The tables and the relations between them should be generated.

Above we created one abstract class – BaseEntityClass, two entities – Pizza and Toppings and one enumeration – PizzaaSize. After running the application the scheme and the tables of this database should be created in your mysql. We are using mysql lokal hosting for this example. It looks like this:

Entities IntelliJ Java Spring Boot
Entities IntelliJ Java Spring Boot
The entities from the Java Spring Boot in MySQL DB
The entities from the Java Spring Boot in MySQL DB

Repositories

A repository in Java Spring Boot is a specialized interface that facilitates interaction with the database by offering built-in methods for common operations such as saving, retrieving, updating, and deleting data. Repositories eliminate the need for boilerplate code and provide an easy-to-use, declarative way to manage entities.

Repositories are defined as interfaces by extending Spring Data JPA interfaces such as JpaRepository (Extends CRUD functionality with pagination and sorting feature), CrudRepository (Provides basic CRUD operations), or PagingAndSortingRepository (Adds pagination and sorting support).

Spring Boot automatically implements the repository interfaces and makes them available as Spring Beans for dependency injection. Developers can use these repositories to perform data operations directly.

Services

In Java Spring Boot, services play a pivotal role in implementing the business logic of an application. They act as an intermediary layer between the controller (presentation layer) and the repository (data access layer). By encapsulating business rules and application-specific logic, services promote a modular, clean, and maintainable architecture.

A service in Java Spring Boot is a specialized component annotated with @Service. It is responsible for executing business logic, orchestrating workflows, and interacting with repositories to fetch or manipulate data. Services often contain methods that represent the operations or behaviors of your application’s domain.

A service class is annotated with @Service, signaling Java Spring Boot to manage it as a Spring Bean. It contains methods that encapsulate business operations.

Inject Dependencies
Services typically depend on repositories and sometimes other services. These dependencies are injected using @Autowired or constructor-based injection.

Invoke from Controllers
Controllers invoke service methods to handle incoming requests and execute the associated business logic.

Controllers

In Java Spring Boot, a Controller is a class annotated with @Controller or @RestController that serves as the entry point for handling HTTP requests. It acts as a bridge between the user interface (frontend or client) and the business logic layer of the application.

What Happens When You Run a Class with @SpringBootApplication?

  1. Java Spring Boot Application Context Initialization:
    • The @SpringBootApplication annotation triggers the auto-configuration, component scanning, and initialization of the Spring application context.
  2. Component Scanning:
    • Spring scans for components like @Controller, @RestController, @Service, @Repository, etc., within the package and its sub-packages where the @SpringBootApplication class resides.
    • During this scanning process, it detects your controller and registers it as a Spring bean.
  3. Embedded Server Startup:
    • Spring Boot starts an embedded server (e.g., Tomcat) if you’re building a web application. This server listens for incoming HTTP requests.
  4. Controller Readiness:
    • The methods in your controller are mapped to specific HTTP endpoints (defined by @GetMapping, @PostMapping, etc.), but they are not called immediately.
    • Instead, the controller sits idle, waiting for incoming HTTP requests.

When Does the Controller Get Called?

The controller methods are called only when an HTTP request matches their endpoint. For example:

javaCode kopieren@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}
  • When you run the application:
    • The @SpringBootApplication annotated class starts the Spring context.
    • The controller is discovered and registered.
    • The server begins listening for requests.
  • The controller method (sayHello) will execute only if you send a request to http://localhost:8080/api/hello.

Key Takeaway

Running the class with @SpringBootApplication does not automatically call the controller. Instead:

  • The controller is registered and waits for HTTP requests.
  • You must send a request to the mapped endpoint to trigger the controller method.

Java Spring Boot Basics
Java Spring Boot Basics
error: Content is protected !!