2. Product Catalog Service‐ PostgreSQL Edition ‐ (Java Maven Spring Boot) - Wiz-DevTech/prettygirllz GitHub Wiki

Product Catalog Service Migration to PostgreSQL (Java + Maven + Spring Boot)

Here's the fully updated implementation guide with all MongoDB references replaced for your PostgreSQL database configuration:


1. Prerequisites Setup

1.1 Install Tools

bash
Copy
Download
# Java & Maven
sudo apt install openjdk-17-jdk maven

# PostgreSQL (Docker) docker run -d -p 5432:5432 --name postgres </span> -e POSTGRES_USER=gateway </span> -e POSTGRES_PASSWORD=secret </span> -e POSTGRES_DB=gateway_cache </span> postgres:15

1.2 Verify Connection

bash
Copy
Download
psql -h localhost -p 5432 -U gateway -d gateway_cache
# Password: secret

2. Project Structure (Maven)

Copy
Download
src/
├── main/
│   ├── java/
│   │   ├── com.productcatalog/
│   │   │   ├── model/            # JPA Entities
│   │   │   ├── repository/       # PostgreSQL Repositories
│   │   │   ├── service/          # Business Logic
│   │   │   └── ProductCatalogApplication.java
│   └── resources/
│       ├── application.yml       # PostgreSQL Config
│       ├── db/
│       │   └── migration/       # Flyway scripts (optional)
│       └── logback.xml
└── test/                        # JUnit tests

3. PostgreSQL Dependencies (pom.xml)

xml
Copy
Download
Run
<dependencies>
<!-- Spring Data JPA for PostgreSQL -->
<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>

<!-- Flyway for migrations (optional) --> <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> </dependency> </dependencies>


4. PostgreSQL Configuration

4.1 application.yml

yaml
Copy
Download
spring:
datasource:
url: jdbc:postgresql://localhost:5432/gateway_cache
username: gateway
password: secret
hikari:
maximum-pool-size: 10
jpa:
hibernate:
ddl-auto: validate # Match your schema
show-sql: true
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect

4.2 Entity Class (JPA)

java
Copy
Download
@Entity
@Table(name = "skus")
public class SKU {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "code", unique = true, length = 8) private String code; // Format: "ABC-1234"

@Column(name = "inventory") private int inventory; }


5. PostgreSQL Repository Layer

java
Copy
Download
public interface SKURepository extends JpaRepository<SKU, Long> {
@Query("SELECT s FROM SKU s WHERE s.code = :code")
Optional<SKU> findByCode(@Param("code") String code);
}

6. Service Layer Updates

java
Copy
Download
@Service
@Transactional
public class SKUService {
@Autowired
private SKURepository skuRepo;

public void createSKU(SKU sku) { // PostgreSQL will enforce the UNIQUE constraint skuRepo.save(sku); } }


7. Database Schema Management

Option A: Hibernate Auto-DDL

yaml
Copy
Download
spring:
jpa:
hibernate:
ddl-auto: update # For dev only

Option B: Flyway (Recommended)

  1. Create src/main/resources/db/migration/V1__Create_skus_table.sql:

sql
Copy
Download
CREATE TABLE skus (
id BIGSERIAL PRIMARY KEY,
code VARCHAR(8) UNIQUE NOT NULL CHECK (code ~ '^[A-Z]{3}-\d{4}$'),
inventory INTEGER NOT NULL DEFAULT 0
);

8. Testing with PostgreSQL

8.1 Integration Test

java
Copy
Download
@SpringBootTest
@Testcontainers
public class SKUServiceIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");

@DynamicPropertySource static void configureProperties(DynamicPropertyRegistry registry) { registry.add("spring.datasource.url", postgres::getJdbcUrl); registry.add("spring.datasource.username", postgres::getUsername); registry.add("spring.datasource.password", postgres::getPassword); }

@Test void testSkuPersistence() { SKU sku = new SKU("ABC-1234", 100); skuRepo.save(sku); assertNotNull(sku.getId()); } }


9. Maven Build & Run

9.1 Standard Execution

bash
Copy
Download
mvn spring-boot:run

9.2 Docker Deployment

dockerfile
Copy
Download
FROM eclipse-temurin:17-jdk
COPY target/product-catalog-0.0.1.jar app.jar
ENTRYPOINT ["java","-jar","app.jar"]

Build and run:

bash
Copy
Download
mvn clean package
docker build -t product-catalog .
docker run -p 8080:8080 --network host product-catalog

10. Key PostgreSQL Features

 ACID Compliance: Full transaction support
 SQL Joins: Efficient relational queries
 Constraints:

sql
Copy
Download
ALTER TABLE skus ADD CONSTRAINT valid_sku_format
CHECK (code ~ '^[A-Z]{3}-\d{4}$');

 Performance: Table partitioning, materialized views


Troubleshooting

Issue Solution
Connection refused Verify PostgreSQL is running: docker ps
Authentication failed Check application.yml credentials
Schema validation errors Match entity fields with table columns

Migration Checklist

  1. Replace MongoDB dependencies with PostgreSQL

  2. Update entity annotations (@Entity instead of @Document)

  3. Configure connection pooling (HikariCP)

  4. Implement schema management (Flyway/Hibernate)

  5. Update tests for PostgreSQL


Why This Works with Maven

  • Dependency Management: Maven handles PostgreSQL driver and Spring Data JPA

  • Build Consistency: Same mvn clean install workflow

  • Test Support: testcontainers for integration testing

Ready to deploy with your exact configuration:

  • Host: localhost:5432

  • Database: gateway_cache

  • Credentials: gateway/secret


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