ZetCode

Spring Boot findAll

last modified March 25, 2021

Spring Boot findAll shows how to retrieve all entities using findAll method of the CrudRepository.

Spring is a popular Java/Kotlin application framework for creating enterprise applications. Spring Boot is an evolution of Spring framework which helps create stand-alone, production-grade Spring based applications with minimal effort.

CrudRepository

CrudRepository interface provides generic CRUD operations on a repository for a specific type. Its findAll method retrieves all entities of the type.

Spring Boot findAll example

The following application sets up a repository of City objects. In the console runner we retrieve city objects by their Ids.

build
build.gradle.kts
gradle
gradle.properties
gradlew
gradlew.bat
settings.gradle.kts
src
├── main
│   ├── kotlin
│   │   └── com
│   │       └── zetcode
│   │           ├── Application.kt
│   │           ├── model
│   │           │   └── City.kt
│   │           ├── MyRunner.kt
│   │           ├── repository
│   │           │   └── CityRepository.kt
│   │           └── service
│   │               ├── CityService.kt
│   │               └── ICityService.kt
│   └── resources
│       ├── application.properties
│       ├── data-h2.sql
│       └── schema-h2.sql
└── test
    ├── kotlin
    └── resources

This is the project structure.

build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.4.4"
    id("io.spring.dependency-management") version "1.0.11.RELEASE"
    kotlin("jvm") version "1.4.31"
    kotlin("plugin.spring") version "1.4.31"
    kotlin("plugin.jpa") version "1.4.31"
}

group = "com.zetcode"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    runtimeOnly("com.h2database:h2")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "11"
}

The build.gradle.kts file contains dependencies for Spring Data JPA and H2 database.

resources/application.properties
spring.main.banner-mode=off
spring.datasource.platform=h2
spring.jpa.hibernate.ddl-auto=none

The application.properties is Spring Boot's main configuration file. The Spring Boot banner is turned off with the spring.main.banner-mode property.

The spring.datasource.platform sets the vendor name of the database. It is used in the initialization scripts. The spring.jpa.hibernate.ddl-auto disables the automatic creation of schemas from entities.

resources/schema-h2.sql
CREATE TABLE cities(id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255), population INT);

When the application is started, the schema-h2.sql script is executed. It creates a new database table.

resources/data-h2.sql
INSERT INTO cities(name, population) VALUES('Bratislava', 432000);
INSERT INTO cities(name, population) VALUES('Budapest', 1759000);
INSERT INTO cities(name, population) VALUES('Prague', 1280000);
INSERT INTO cities(name, population) VALUES('Warsaw', 1748000);
INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000);
INSERT INTO cities(name, population) VALUES('New York', 8550000);
INSERT INTO cities(name, population) VALUES('Edinburgh', 464000);
INSERT INTO cities(name, population) VALUES('Suzhou', 4327066);
INSERT INTO cities(name, population) VALUES('Zhengzhou', 4122087);
INSERT INTO cities(name, population) VALUES('Berlin', 3671000);

The table is filled with data from the data-h2.sql file.

com/zetcode/model/City.kt
package com.zetcode.model

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.Table

@Entity
@Table(name = "cities")
class City(
    @Id @GeneratedValue var id: Long = 0,
    var name: String = "",
    var population: Int = 0
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as City

        if (name != other.name) return false
        if (population != other.population) return false

        return true
    }

    override fun hashCode(): Int {
        var result = name.hashCode()
        result = 31 * result + population
        return result
    }

    override fun toString(): String {
        return "City(id=$id, name='$name', population=$population)"
    }
}

This is the City entity.

com/zetcode/repository/CityRepository.kt
package com.zetcode.repository

import com.zetcode.model.City

import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository

@Repository
interface CityRepository : CrudRepository<City, Long>

By extending from the Spring CrudRepository, we have some basic methods for our data repository implemented.

com/zetcode/service/ICityService.kt
package com.zetcode.service

import com.zetcode.model.City

interface ICityService {

    fun findAll(): Iterable<City>
}

ICityService provides a contract method to retrieve all cities.

com/zetcode/service/CityService.java
package com.zetcode.service

import com.zetcode.repository.CityRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class CityService : ICityService {

    @Autowired
    private lateinit var cityRepository: CityRepository

    override fun findAll() = cityRepository.findAll()
}

CityService contains the implementation of the findAll method. We use the repository to retrieve data from the database.

@Autowired
private lateinit var cityRepository: CityRepository

CityRepository is injected.

override fun findAll() = cityRepository.findAll()

The findAll returns the Iterable<City>.

com/zetcode/MyRunner.kt
package com.zetcode

import com.zetcode.service.ICityService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.stereotype.Component

@Component
class MyRunner : CommandLineRunner {

    @Autowired
    private lateinit var cityService: ICityService

    override fun run(vararg args: String?) {

        val cities = cityService.findAll()
        cities.forEach { println(it) }
    }
}

In the MyRunner, we retrieve all cities.

val cities = cityService.findAll()
cities.forEach { println(it) }

We get all cities and print them to the console.

com/zetcode/Application.kt
package com.zetcode

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class Application

fun main(args: Array<String>) {

    runApplication<Application>(*args)
}

The Application sets up the Spring Boot application. The @SpringBootApplication enables auto-configuration and component scanning.

$ ./gradlew bootRun
...
City(id=1, name='Bratislava', population=432000)
City(id=2, name='Budapest', population=1759000)
City(id=3, name='Prague', population=1280000)
City(id=4, name='Warsaw', population=1748000)
City(id=5, name='Los Angeles', population=3971000)
City(id=6, name='New York', population=8550000)
City(id=7, name='Edinburgh', population=464000)
City(id=8, name='Suzhou', population=4327066)
City(id=9, name='Zhengzhou', population=4122087)
City(id=10, name='Berlin', population=3671000)
...

We run the application.

In this tutorial, we have showed how to find all entities using CrudRepository's findAll method.

List all Spring Boot tutorials.