Build a CRUD application with Hibernate and PostgreSQL
A CRUD application handles four basic data operations: create, read, update and delete. This Java build exposes them through REST endpoints while Hibernate maps objects to PostgreSQL tables. That reduces repetitive SQL without hiding how persistence works.
Spring Boot supplies the runtime, while Maven manages dependencies. Entities describe data, repositories perform persistence, services coordinate rules, and controllers handle HTTP. Separating these layers keeps the result testable and easier to extend.
You will build a customer resource, validate requests, handle missing records and test the complete flow. The same design supports booking systems, order tools and internal dashboards used by organisations in Sydney, Melbourne, Brisbane and regional centres.
Australian context matters: a request needed by arvo means the afternoon deadline, not a vague future date. Records may involve Australian dollars, GST and Australian Business Numbers, while teams often serve several time zones. These are product requirements, not afterthoughts.
Setting up the project and database
Start with a supported Java LTS, Spring Boot 3.x, Maven and PostgreSQL. Include the Spring Data JPA starter, PostgreSQL JDBC driver, web starter, Bean Validation and Flyway. Use a local PostgreSQL container where possible because an in-memory database can conceal dialect, constraint and locking differences.
Keep credentials in environment variables and disable open session-in-view. For a local profile, the configuration can be small:
spring:
datasource:
url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/crud_app}
username: ${DATABASE_USERNAME:app}
password: ${DATABASE_PASSWORD:app}
jpa:
hibernate:
ddl-auto: validate
open-in-view: false
Using validate prevents Hibernate from changing production tables. Versioned Flyway migrations will manage the schema later, keeping database changes visible and repeatable across local, test and production environments.
Mapping customers with Hibernate
The entity represents a database table, not a JSON response. A customer needs a generated identifier, a required name and email, an optional Australian Business Number and a version field for concurrency control.
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(nullable = false)
private String name;
@NotBlank
@Email
@Column(nullable = false, length = 320, unique = true)
private String email;
@Column(length = 11)
private String abn;
@Version
private long version;
// Getters and setters
}
Map constraints explicitly so the API contract and PostgreSQL schema agree. Normalise email addresses before applying the unique constraint because PostgreSQL compares text case literally. Store business numbers without spaces, validate their 11-digit format and keep them optional for consumer customers.
Building repositories and service logic
JpaRepository already provides save, findById, findAll and deleteById. Add a derived query only when the application needs it:
public interface CustomerRepository
extends JpaRepository<Customer, Long> {
Optional<Customer> findByEmail(String email);
}
Keep database access inside repositories and transaction boundaries inside services. A write method should load an entity, apply changes and save it within one transaction. Return request and response objects from the web layer so persistence changes do not accidentally alter the public API.
For updates, treat a missing identifier as a not-found result. For creates, rely on a database unique constraint to prevent duplicate emails even if two requests race, then translate that constraint failure into a conflict response. Read-only operations can use @Transactional(readOnly = true).
Exposing CRUD endpoints
Give each route one clear purpose: GET /api/customers lists records, GET /api/customers/{id} reads one, POST creates, PUT or PATCH updates, and DELETE removes it. Apply @Valid to request bodies and convert validated request objects to entities inside the service.
Return 201 Created with a Location header after a successful insert, 204 No Content after deletion, 404 Not Found for an unknown identifier and 409 Conflict for a duplicate email. Protect the endpoints with Spring Security where customer data is involved, and never accept a customer identifier supplied in the request body.
Handling validation and concurrency
Bean Validation catches blank names or malformed email addresses early, while PostgreSQL constraints provide the final guarantee. Use Jakarta annotations such as @NotBlank, @Email and @Size, then translate DataIntegrityViolationException into a clear 409 problem response. Avoid exposing SQL messages or stack traces to clients.
The version field enables optimistic locking so simultaneous updates do not overwrite each other. Services should run writes transactionally and roll back the complete operation when it fails. Catch the lock failure and ask the caller to reload the current record. If audit timestamps are included, store them in UTC and render them in the relevant Australian state time zone.
Preparing tests and schema changes
Test service rules with unit tests, but use Testcontainers with PostgreSQL for repository and endpoint integration tests. Cover list, fetch, create, update and delete, plus invalid email, missing identifier and duplicate email. MockMvc or REST Assured can verify both status codes and response bodies.
Flyway should own schema changes in every environment; avoid Hibernate’s destructive update mode in production. Before altering a live column or constraint, follow a database migration guide to plan backward-compatible changes. A first migration can create the table expected by the entity:
CREATE TABLE customers (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(320) NOT NULL UNIQUE,
abn VARCHAR(11),
version BIGINT NOT NULL DEFAULT 0
);
Use these implementation checks while building:
- Pin Java and Spring Boot versions, and keep database credentials in environment variables.
- Create a versioned Flyway schema instead of relying on Hibernate to alter tables.
- Validate request objects and map duplicate records to
409 Conflict. - Exercise every create, read, update and delete path against PostgreSQL.
Before release, confirm:
- Billing fields use integer cents in Australian dollars, with GST treatment recorded explicitly.
- Australian Business Numbers are optional, space-free and checked against the expected format.
- Managed PostgreSQL runs in an Australian AWS or Azure region where residency matters, with backups and monitoring enabled.
- UTC timestamps are rendered in the appropriate Australian state time zone.