spring postgres connection - Neethahiremath/Wiki GitHub Wiki

add the dependency in pom


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

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

add the properties in yml


 jpa:
      show-sql: false
      database-platform: org.hibernate.dialect.PostgreSQLDialect
      hibernate:
        ddl-auto: update
      properties:
        hibernate:
          order_updates: true
          generate_statistics: false
          jdbc:
            batch_size: 20
            lob:
              non_contextual_creation: true


add the data source for auto configuration in yml


spring:
   datasource:
     initialization-mode: always
     driverClassName: org.postgresql.Driver
     platform: postgres
     url:  jdbc:postgresql://localhost:5432/postgres
     username: username
     password: password
     validationQuery: SELECT 1
     testWhileIdle: true

if you want password to be picked from vault or other location, use the bean to create the datasource


   @Bean
    @Primary
    public HikariDataSource dataSource() {

return DataSourceBuilder.create()
.type(HikariDataSource.class)
.url(properties.getUrl())
.username(properties.getUsername())
.password(properties.getPassword())
.build();
    }

create repository

@Repository
public interface Repository extends JpaRepository<Entity,Id> {

}

or 

public interface Repository extends PagingAndSortingRepository<Entity, Key> {
    Optional<List<Entity>> findById(String id);
}


create Entity class for ORM


@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@IdClass(Key.class)
@Table(name = "table")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Entity {

    @Id
    @Column(name = "id")
    private String id;

}

Key class is the key of table



@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Key implements Serializable {

    private String id;
}

use the repository in service class for accessing the table data.

⚠️ **GitHub.com Fallback** ⚠️