Spring Boot - Postgres

Spring Boot Integration with Postgres

Maven Dependencies

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

Run MySQL using Docker Compose

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Use postgres/example user/password credentials
version: '3.9'

services:

db:
image: postgres
restart: always
# set shared memory limit when using docker-compose
shm_size: 128mb
# or set shared memory limit when deploy via swarm stack
#volumes:
# - type: tmpfs
# target: /dev/shm
# tmpfs:
# size: 134217728 # 128*2^20 bytes = 128Mb
environment:
POSTGRES_PASSWORD: example
ports:
- 127.0.0.1:5432:5432

adminer:
image: adminer
restart: always
ports:
- 8000:8080

Configuration for a MySQL dataSource

application.properties

1
2
3
4
5
6
7
8
9
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=example
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Jpa Entity and Repository

Entity

1
2
3
4
5
6
7
8
9
10
11
12
@Entity
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class Customer {
@Id
private long id;
private String name;
private String email;
private String password;
}

Repository

1
2
3
@Repository
public interface CustomerRepo extends JpaRepository<Customer, Long> {
}

To test

1
2
3
4
5
6
7
8
9
10
@Bean
public CommandLineRunner runCLR(CustomerRepo userRepo){
return new CommandLineRunner(){
@Override
public void run(String... args) throws Exception {
userRepo.save(new Customer().setName("John Doe").setEmail("abc@def.com").setPassword("1234"));
userRepo.findAll().forEach(System.out::println);
}
};
}

Output in console

1
Customer(id=0, name=John Doe, email=abc@def.com, password=1234)