Java application properties postgresql

Spring Boot Connect to PostgreSQL Database Examples

Through this Spring Boot tutorial, you will learn how to configure and write code for connecting to a PostgreSQL database server in a Spring Boot application. I’ll share with you the two common ways:

  • Use Spring JDBC with JdbcTemplate to connect to a PostgreSQL database
  • Use Spring Data JPA to connect to a PostgreSQL database
  • Add a dependency for PostgreSQL JDBC driver, which is required to allow Java applications to be able to talk with a PostgreSQL database server.
  • Configure data source properties for the database connection information
  • Add a dependency for Spring JDBC or Spring Data JPA, depending on your need:
    • Use Spring JDBC for executing plain SQL statements
    • Use Spring Data JPA for more advanced use, e.g. mapping Java classes to tables and Java objects to rows, and take advantages of the Spring Data JPA API.

    1. Add dependency for PostgreSQL JDBC Driver

     org.postgresql postgresql runtime 

    This will use the default version specified by Spring Boot. If you want to explicitly specify a PostgreSQL JDBC version, refer to this page.

    2. Configure Data Source Properties

    Next, you need to specify some database connection information in the Spring Boot application configuration file ( application.properties ) as follows:

    spring.datasource.url=jdbc:postgresql://localhost:5432/shopme spring.datasource.username=postgres spring.datasource.password=password

    Here, the JDBC URL points to a PostgreSQL database server running on localhost. Update the JDBC URL, username and password according to your environment.

    3. Connect to PostgreSQL Database with Spring JDBC

    In the simplest case, you can use Spring JDBC with JdbcTemplate to work with a relational database. So add the following dependency to your Maven project file:

     org.springframework.boot spring-boot-starter-jdbc 

    And the following code example is of a Spring Boot console program uses JdbcTemplate to execute a SQL Insert statement:

    package net.codejava; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.jdbc.core.JdbcTemplate; @SpringBootApplication public class SpringJdbcTemplate2PostgreSqlApplication implements CommandLineRunner < @Autowired private JdbcTemplate jdbcTemplate; public static void main(String[] args) < SpringApplication.run(SpringJdbcTemplate2PostgreSqlApplication.class, args); >@Override public void run(String. args) throws Exception < String sql = "INSERT INTO students (name, email) VALUES (" + "'Nam Ha Minh', 'nam@codejava.net')"; int rows = jdbcTemplate.update(sql); if (rows >0) < System.out.println("A new row has been inserted."); >> >

    This program will insert a new row into the students table in a PostgreSQL database, using Spring JDBC which is a thin API built on top of JDBC.

    For details about using Spring JdbcTemplate, I recommend you to read this tutorial.

    4. Connect to PostgreSQL Database with Spring Data JPA

    If you want to map Java classes to tables and Java objects to rows and take advantages of an Object-Relational Mapping (ORM) framework like Hibernate, you can use Spring Data JPA. So declare the following dependency to your project:

     org.springframework.boot spring-boot-starter-data-jpa 

    Besides the JDBC URL, username and password, you can also specify some additional properties as follows:

    spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect

    And you need to code an entity class (a POJO Java class) to map with the corresponding table in the database, as follows:

    package net.codejava; import javax.persistence.*; @Entity @Table(name = "students") public class Student < @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String email; // getters and setters. >

    package net.codejava; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository

    @Controller public class StudentController < @Autowired private StudentRepository studentRepo; @GetMapping("/students") public String listAll(Model model) < ListlistStudents = studentRepo.findAll(); model.addAttribute("listStudents", listStudents); return "students"; > >

    I recommend you to follow this article: Understand Spring Data JPA with Simple Example to learn more about Spring Data JPA.

    Those are some code examples for connecting to PostgreSQL database in Spring Boot. As you have seen, Spring Boot greatly simplifies the programming, and you can choose to use Spring JDBC or Spring Data JPA.

    Watch the following video to see the coding in action:

    Other Spring Boot Tutorials:

    • How to create a Spring Boot Web Application (Spring MVC with JSP/ThymeLeaf)
    • Spring Boot CRUD Example with Spring MVC – Spring Data JPA – ThymeLeaf — Hibernate — MySQL
    • Spring Boot Hello World RESTful Web Services Tutorial
    • Spring Boot Thymeleaf Form Handling Tutorial
    • Spring Data JPA Paging and Sorting Examples
    • Spring Boot Error Handling Guide
    • Spring Boot Logging Basics
    • Spring Security Role-based Authorization Tutorial
    • Spring Security Customize Login and Logout
    • How to Get Logged-in User’s Details with Spring Security
    • Spring Security: Prevent User from Going Back to Login Page if Already logged in

    About the Author:

    Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

    Add comment

    Comments

    spring.jpa.properties.hibernate.dialect is incorrect, i think it should be
    org.hibernate.dialect.PostgreSQL8Dialect

    Источник

    Spring Boot PostgreSQL Configuration: Maven & Gradle

    spring boot tutorial

    If you’re looking to build a Java Spring application that utilizes a PostgreSQL database, you’re in luck. Spring Boot makes it simple to integrate with a variety of data sources, including PostgreSQL. In this blog, we’ll walk you through how to connect your Postgres database to your Spring Boot project, assuming you already have PostgreSQL installed on your system. If you need help installing PostgreSQL, please refer to blog.

    1. Add PostgreSQL dependency

    First, you’ll need to add the PostgreSQL driver dependency to your project. You can do this by adding the following code to your build.gradle or pom.xml file, depending on whether you’re using Gradle or Maven:

      org.postgresql postgresql 42.3.1  

    2. Add PostgreSQL properties to application.properties file

    Next, you’ll need to add the appropriate properties to your application.properties file. Here are the required properties for connecting to a PostgreSQL database:

    spring.datasource.url=jdbc:postgresql://localhost:5432/ spring.datasource.username= spring.datasource.password= spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

    Note that you’ll need to replace , , and with the appropriate values for your PostgreSQL database.

    3. Create an Entity Class

    Next, you’ll need to create an entity class that maps to a table in your PostgreSQL database. Here’s an example:

    @Entity @Table(name = "users") public class User < @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; private String email; // getters and setters >

    4. Create a Repository Interface

    Next, you’ll need to create a repository interface that extends the JpaRepository interface. Here’s an example:

    @Repository public interface UserRepository extends JpaRepository

    5. Use your Repository in your Controller

    Finally, you’ll need to use your repository in your controller to retrieve data from your PostgreSQL database. Here’s an example:

    @RestController @RequestMapping("/api/users") public class UserController < @Autowired private UserRepository userRepository; @GetMapping public ListgetUsers() < return userRepository.findAll(); >// other controller methods >

    Congratulations! You’ve successfully connected your PostgreSQL database to your Spring Boot project. Now you’re ready to start building your application.

    In conclusion, connecting PostgreSQL to your Spring Boot project is a simple and powerful way to improve your application’s functionality and capabilities. By following the steps outlined in this guide, you can easily add PostgreSQL properties, create entity classes and repositories, and use them in your controller to retrieve data. With Spring Boot’s rich ecosystem of libraries and features, you can take your application to the next level and provide even more value to your users.

    Источник

    Читайте также:  Питон для егэ 2021
Оцените статью