Spring Boot + Spring data JPA + PostgreSQL

spring boot spring data jpa postgresql

The previous Spring Boot + Spring data JPA will be reused, modify to support PostgreSQL database.

Technologies used :

  • Spring Boot 2.1.2.RELEASE
  • Spring 5.1.4.RELEASE
  • Hibernate 5.3.7
  • HikariCP 3.2.0
  • PostgreSQL driver 42.2.5
  • Maven 3
  • Java 8

Puts a postgresql driver and defined the data source url in application.properties. Done, Spring Boot is able to connect to a PostgreSQL database.

pom.xml

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

1. Maven

pom.xml

<?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 
		 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-boot-data-jpa</artifactId>
    <packaging>jar</packaging>
    <name>Spring Boot Spring Data JPA</name>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <downloadSources>true</downloadSources>
        <downloadJavadocs>true</downloadJavadocs>
    </properties>

    <dependencies>

        <!-- jpa, crud repository -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- PostgreSQL -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </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>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.0</version>
            </plugin>

        </plugins>

    </build>
</project>

2. Configure PostgreSQL

2.1 Update the PostgreSQL settings in spring.datasource.*

application.properties

## default connection pool
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

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

#drop n create table again, good for testing, comment this in production
spring.jpa.hibernate.ddl-auto=create

Done.

Download Source Code

$ git clone https://github.com/mkyong/spring-boot.git
$ cd spring-data-jpa-postgresql
$ mvn spring-boot:run

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
1 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
Richa GuptauriSajeesh MuraliShebin Recent comment authors
newest oldest most voted
uri
Guest
uri

This tutorial is quite bad, no explanations to get it working

Richa Gupta
Guest
Richa Gupta

i have followed it But My application is failing to start. I get following error –

Error starting ApplicationContext. To display the auto-configuration report re-run your application with ‘debug’ enabled.
2019-08-12 14:14:11.370 ERROR 7066 — [ main] o.s.b.d.LoggingFailureAnalysisReporter :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field xEventRepository in com.package.myBuilder required a bean named ‘entityManagerFactory’ that could not be found.

Action:

Consider defining a bean named ‘entityManagerFactory’ in your configuration.

Process finished with exit code 1

Shebin
Guest
Shebin

Please help. I am getting this error during startup. With mysql it just works fine. 2019-07-02 18:10:07.588 INFO 912 — [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete 2019-07-02 18:10:07.757 INFO 912 — [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit ‘default’ 2019-07-02 18:10:10.451 INFO 912 — [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@56113384, org.springframework.security.web.context.SecurityContextPersistenceFilter@4372b9b6, org.springframework.security.web.header.HeaderWriterFilter@34cdeda2, org.springframework.security.web.authentication.logout.LogoutFilter@66746f57, murraco.security.JwtTokenFilter@5669c5fb, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4b41e4dd, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@42721fe, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@373ebf74, org.springframework.security.web.session.SessionManagementFilter@305a0c5f, org.springframework.security.web.access.ExceptionTranslationFilter@75cd8043, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@4a194c39] 2019-07-02 18:10:11.202 INFO 912 — [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1ee0005: startup date [Tue Jul 02 18:08:30 IST 2019]; root of context hierarchy 2019-07-02 18:10:11.446 INFO 912 — [ main]… Read more »

Shebin
Guest
Shebin

This is my user model

@Entity
public class User {

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

@Size(min = 4, max = 255, message = “Minimum username length: 4 characters”)
@Column(unique = true, nullable = false)
private String username;

@Column(unique = true, nullable = false)
private String email;

Sajeesh Murali
Guest
Sajeesh Murali

I am new to Java .. I am getting below exception while running project Exception during pool initialization.”,”exception”:”org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections Below steps followed Am I doing anything wrong ? i have ran docker image docker run –name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres my application.yml looks as below spring: application: name: eksterntjenestepensjon datasource: url: jdbc:postgresql://localhost:5432/postgres username: postgres password: password hikari: connectionTimeout: 20000 maximumPoolSize: 5 jpa: hibernate: ddl-auto: create profiles: active: dev