📜  spring boot postgres - Java (1)

📅  最后修改于: 2023-12-03 15:20:12.600000             🧑  作者: Mango

Spring Boot Postgres - Java

Introduction

Spring Boot is a popular framework for building web applications in Java. It provides a simple and efficient way to create standalone, production-grade Spring-based applications. Postgres is an open-source relational database management system that is widely used by developers. In this tutorial, we will explore how to integrate Spring Boot with Postgres and create a simple web application.

Prerequisites

To follow the steps in this tutorial, you will need the following software installed on your system:

  • Java 8 or later
  • Maven
  • Postgres
Project Setup

We will start by creating a new Spring Boot project using the Spring Initializr. Open your terminal and run the following command to create a new project:

$ mkdir spring-boot-postgres && cd spring-boot-postgres
$ mvn archetype:generate -DgroupId=com.example -DartifactId=spring-boot-postgres -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Next, we will add the required dependencies for our project. Add the following dependencies to the pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.2.24</version>
</dependency>

This will add the necessary dependencies for Spring Boot, JPA, and Postgres.

Configure Postgres

Next, we will configure our Postgres database. Open the application.properties file in your project's src/main/resources directory and add the following:

spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=create

This will configure our application to use the Postgres database running on the local machine with the username postgres and password postgres. We are also setting the ddl-auto property to create, which tells Hibernate to create the database schema when the application starts.

Create Entity and Repository

We will now create a simple entity that represents a person with a name and email address. Create a new Java class called Person under the package com.example.springbootpostgres.model and add the following code:

package com.example.springbootpostgres.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "person")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "email", nullable = false)
    private String email;

    public Person() {}

    public Person(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // getters and setters
}

This will create a simple entity with two properties, name and email. We are using JPA annotations to define the entity and table names, as well as the column names and data types.

Next, we will create a repository for our Person entity. Create a new interface called PersonRepository under the package com.example.springbootpostgres.repository and add the following code:

package com.example.springbootpostgres.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.springbootpostgres.model.Person;

public interface PersonRepository extends JpaRepository<Person, Long> {
}

This will create a simple repository that extends the JpaRepository interface. This interface provides a set of methods for working with entities in the database.

Create Controller

Finally, we will create a web controller that handles HTTP requests and responses. Create a new Java class called PersonController under the package com.example.springbootpostgres.controller and add the following code:

package com.example.springbootpostgres.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.springbootpostgres.model.Person;
import com.example.springbootpostgres.repository.PersonRepository;

@RestController
public class PersonController {

    @Autowired
    private PersonRepository personRepository;

    @GetMapping("/persons")
    public List<Person> getAllPersons() {
        return personRepository.findAll();
    }

    @GetMapping("/persons/{id}")
    public ResponseEntity<Person> getPersonById(@PathVariable(value = "id") Long personId) {
        Person person = personRepository.findById(personId)
                .orElseThrow(() -> new RuntimeException("Person not found"));

        return ResponseEntity.ok().body(person);
    }

    @PostMapping("/persons")
    public Person createPerson(@RequestBody Person person) {
        return personRepository.save(person);
    }
}

This will create a simple controller with three endpoints:

  • GET /persons - returns a list of all persons in the database
  • GET /persons/{id} - returns the person with the specified ID
  • POST /persons - adds a new person to the database

We are using Spring's @RestController annotation to mark this class as a web controller. We are also using @Autowired to inject the PersonRepository instance into this class.

Run the Application

We are now ready to run our application. Open your terminal and run the following command in your project directory:

$ mvn spring-boot:run

This will start the Spring Boot application and create the necessary database schema in Postgres.

Conclusion

In this tutorial, we learned how to integrate Spring Boot with Postgres and create a simple web application. We created an entity, repository and controller to manage the data. We also configured the Postgres database and ran the application using Maven. This is just the beginning, you can now go ahead and explore more features of Spring Boot and Postgres to build robust and scalable applications.