How do I create a starfield animation in Java Swing?

You can simulate flying through stars by assigning each star a depth and projecting its position onto a two-dimensional panel. As the depth decreases, the star moves farther from the center of the screen and appears larger.

Starfield Warp
Starfield Warp

This SwingLoops example draws 420 stars with short light trails. It uses Java Swing and Java 2D without a 3D engine, external libraries, or image assets.

Source code

Save the following code as StarfieldWarp.java:

import java.awt.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;

public class StarfieldWarp extends JPanel {
    private static final int WIDTH = 450;
    private static final int HEIGHT = 800;
    private static final int COUNT = 420;
    private static final double CYCLE = 12.0;
    private static final double FOCAL = 260.0;

    private final double[] x = new double[COUNT];
    private final double[] y = new double[COUNT];
    private final double[] offset = new double[COUNT];
    private final Timer timer = new Timer(16, _ -> repaint());
    private long startedAt;

    public StarfieldWarp() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(new Color(5, 9, 20));

        Random random = new Random(42);
        for (int i = 0; i < COUNT; i++) {
            double angle = random.nextDouble() * 2 * Math.PI;
            double radius = 0.12 + 1.8 * Math.sqrt(random.nextDouble());
            x[i] = radius * Math.cos(angle);
            y[i] = radius * Math.sin(angle);
            offset[i] = random.nextDouble();
        }
    }

    @Override
    public void addNotify() {
        super.addNotify();
        startedAt = System.nanoTime();
        timer.start();
    }

    @Override
    public void removeNotify() {
        timer.stop();
        super.removeNotify();
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Graphics2D g = (Graphics2D) graphics.create();

        try {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            double scale = Math.min(
                    getWidth() / (double) WIDTH,
                    getHeight() / (double) HEIGHT);
            g.translate(getWidth() / 2.0, getHeight() / 2.0);
            g.scale(scale, scale);
            g.clipRect(-WIDTH / 2, -HEIGHT / 2, WIDTH, HEIGHT);

            double seconds = (System.nanoTime() - startedAt) / 1e9;
            double phase = (seconds % CYCLE) / CYCLE;

            for (int i = 0; i < COUNT; i++) {
                double progress = (phase + offset[i]) % 1.0;
                double z = 4.0 - 3.8 * progress;

                double screenX = FOCAL * x[i] / z;
                double screenY = FOCAL * y[i] / z;

                double previousZ = Math.min(4.0, z + 0.045);
                double tailX = FOCAL * x[i] / previousZ;
                double tailY = FOCAL * y[i] / previousZ;

                // Hide each star as it enters or leaves its depth cycle.
                double fadeIn = Math.min(1, progress / 0.08);
                double fadeOut = Math.min(1, (1 - progress) / 0.06);
                float alpha = (float) (fadeIn * fadeOut);
                float width = (float) (0.6 + 1.8 * progress);

                g.setColor(new Color(110, 192, 255));
                g.setComposite(
                        AlphaComposite.SrcOver.derive(alpha * 0.13f));
                g.setStroke(new BasicStroke(width + 4f,
                        BasicStroke.CAP_ROUND,
                        BasicStroke.JOIN_ROUND));
                g.draw(new Line2D.Double(
                        tailX, tailY, screenX, screenY));

                g.setColor(new Color(225, 244, 255));
                g.setComposite(AlphaComposite.SrcOver.derive(alpha));
                g.setStroke(new BasicStroke(width,
                        BasicStroke.CAP_ROUND,
                        BasicStroke.JOIN_ROUND));
                g.draw(new Line2D.Double(
                        tailX, tailY, screenX, screenY));
            }
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Starfield Warp");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new StarfieldWarp());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

You need a Java Development Kit and a desktop environment that supports Swing windows.

Open a terminal in the directory containing the file and run:

javac StarfieldWarp.java
java StarfieldWarp

The preferred drawing area is 450 × 800 pixels. Resize the window to fit your display; the drawing preserves its proportions. Close the window to exit.

Give each star a position and a depth

Each star receives fixed horizontal and vertical coordinates, plus a random offset within the animation cycle. The random offsets spread the stars across different depths instead of making them approach together.

The star’s depth decreases over time:

double progress = (phase + offset[i]) % 1.0;
double z = 4.0 - 3.8 * progress;

A star starts at depth 4.0 and approaches depth 0.2 before returning to the far end. The depth stays positive, avoiding division by zero.

The fixed random seed produces the same star arrangement on each run. The animation repeats every 12 seconds because every star completes one depth cycle in that interval.

Project the stars onto the screen

The key equations are:

double screenX = FOCAL * x[i] / z;
double screenY = FOCAL * y[i] / z;

The FOCAL constant converts the star coordinates into logical screen pixels. Dividing by depth creates perspective.

For example, a star with x = 1 is drawn at horizontal coordinate 65 when z = 4, but at coordinate 260 when z = 1. Its horizontal position in space has not changed; its projected position moves outward because it is closer.

This is the same basic relationship that makes nearby objects appear larger than distant ones.

Draw a trail behind each star

The trail begins at a slightly greater depth:

double previousZ = Math.min(4.0, z + 0.045);

Projecting that deeper point places the trail’s tail closer to the screen center. A line from the tail to the current position suggests forward motion.

Despite its name, previousZ is not a stored previous-frame position. It is a fixed depth offset, so the trail does not depend on the repaint rate. Perspective naturally makes the trail longer as the star approaches.

The code draws each line twice: a wide translucent stroke creates a soft halo, and a narrow bright stroke forms the center.

Hide the depth reset

Modulo arithmetic returns a star to the far end when its progress reaches one. Without a fade, that reset could produce a visible jump.

The first 8% of each star’s journey fades in, and the final 6% fades out. At the wrap point, the star is invisible. Many stars also leave the panel’s visible bounds before reaching their nearest depth.

This makes the repeating depth cycle less noticeable while keeping the simulation deterministic.

Animate with Swing

A Swing timer requests repaints approximately every 16 milliseconds. The program calculates motion from elapsed time measured with System.nanoTime(), rather than moving stars a fixed amount per frame.

A delayed repaint therefore skips ahead to the correct position instead of slowing down the animation.

The interface is created on Swing’s event-dispatch thread. The timer starts when the panel becomes displayable and stops when it is removed.

Customize the animation

Setting Effect
COUNT Number of stars.
CYCLE Duration of each depth journey; smaller values increase speed.
FOCAL Projection scale; larger values move stars farther from the center.
0.045 in the tail calculation Trail length in depth units.
Stroke colors Star and halo colors.
0.08 and 0.06 Fade-in and fade-out portions of each journey.

For a first experiment, reduce CYCLE from 12 to 8 seconds. Then increase the tail depth offset to 0.08 to create longer streaks.

The complete source code above is free to copy and run. Explore the SwingLoops repository for more Java animation examples.

How do I create and start a thread in Java?

Use Thread.ofPlatform() to create a platform thread. Pass it a Runnable that describes the work, then call start() to run that work on the new thread.

In this example, a worker thread prints its name, and the main thread waits for it to finish.

Source code

Save the following code as ThreadExample.java:

public class ThreadExample {
    void main() throws InterruptedException {
        Runnable task = () -> {
            String threadName = Thread.currentThread().getName();
            IO.println("Task running on: " + threadName);
        };

        Thread worker = Thread.ofPlatform()
                .name("worker")
                .unstarted(task);

        IO.println("Starting the worker.");
        worker.start();
        worker.join();
        IO.println("The worker has finished.");
    }
}

Explanation

The Runnable describes what the worker should do. Here, a lambda calls Thread.currentThread() to get the thread that is executing the task, then prints its name.

Thread.ofPlatform() returns a thread builder. The name("worker") call sets the thread’s name, and unstarted(task) creates the thread without running the task yet.

The call to worker.start() schedules the task to run on the new thread. If you call task.run() directly, the task runs on the current thread instead.

Waiting for the worker

worker.join() waits until the worker finishes. This ensures that the final message appears after the task’s message. Without join(), the main thread could print its final message before the worker prints anything.

The join() method can throw InterruptedException if the main thread is interrupted while waiting. This example declares that exception in main().

Run the example

Compile and run the file:

javac ThreadExample.java
java ThreadExample

Output

Starting the worker.
Task running on: worker
The worker has finished.

A Thread can be started only once. To run the same task again on a new thread, create another Thread using the same Runnable.

How do I choose an image file format in Java?

In the previous post, we created a transparent image and saved it as PNG. In this example, we will choose formats for different tasks, check the available Image I/O codecs, and export a transparent drawing as PNG and JPEG. The program creates its own image, so you do not need an input file.

Choose a format for your image

A file format describes how an image is stored on disk. A BufferedImage holds decoded pixels in memory. Its type, such as TYPE_INT_ARGB, is separate from the format you use to save those pixels.

Format Compression and transparency Typical use
PNG Lossless; supports full alpha transparency Screenshots, diagrams, icons, and images with text
JPEG Usually lossy; no alpha transparency Photographs where smaller files matter
GIF Lossless compression of indexed colors; up to 256 palette entries per frame and one transparent palette index Small palette graphics and simple animations
BMP Often uncompressed; alpha support varies across variants and software Compatibility with software that specifically requires BMP
TIFF Supports several compression methods; alpha depends on the image layout and reader Scanned documents, publishing, and workflows that need multiple pages or specialized metadata

For a transparent logo, start with PNG. For a photograph, try JPEG and inspect the result. For scans, follow the requirements of the receiving application, which may request TIFF.

GIF compression does not mean an arbitrary full-color image keeps all its colors: converting to a limited palette can change them. GIF also cannot preserve smooth, partially transparent edges. TIFF is a family of capabilities; test the particular compression and image layout required by your workflow.

File size depends on image content, dimensions, and encoder settings. A flat-color diagram can be smaller as PNG than JPEG. Do not assume one format always produces the smallest file.

Check codec support

A reader decodes a file into pixels. A writer encodes pixels into a file. Java 25 supplies standard Image I/O plug-ins for PNG, JPEG, GIF, BMP, TIFF, and WBMP. Additional plug-ins can add formats.

Use ImageIO.getImageReadersByFormatName() and getImageWritersByFormatName() to check registered support. The presence of a writer does not guarantee it accepts every image layout. For example, convert an ARGB image to an opaque RGB image before writing JPEG.

Complete Java example

Save this code as ImageFormatExample.java.

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ImageFormatExample {
    public static void main(String[] args) throws IOException {
        for (String format : new String[]{"png", "jpeg", "gif", "bmp", "tiff", "webp"}) {
            boolean reader = ImageIO.getImageReadersByFormatName(format).hasNext();
            boolean writer = ImageIO.getImageWritersByFormatName(format).hasNext();
            System.out.printf("%s: reader=%s, writer=%s%n", format, reader, writer);
        }

        BufferedImage source = createImage();
        BufferedImage opaque = flatten(source, Color.WHITE);

        Path directory = Path.of("image-formats-output");
        Files.createDirectories(directory);
        saveAndInspect(source, "png", directory.resolve("card.png"));
        saveAndInspect(opaque, "jpeg", directory.resolve("card.jpg"));
        saveAndInspect(opaque, "gif", directory.resolve("card.gif"));
        saveAndInspect(opaque, "bmp", directory.resolve("card.bmp"));
        saveAndInspect(opaque, "tiff", directory.resolve("card.tiff"));
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(
                320, 200, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        try {
            g.setColor(new Color(33, 99, 200));
            g.fillRect(20, 20, 280, 160);
            g.setColor(new Color(255, 120, 0, 128));
            g.fillOval(0, 60, 100, 100);
            g.setColor(Color.WHITE);
            g.drawString("Java image formats", 110, 105);
        } finally {
            g.dispose();
        }
        return image;
    }

    private static BufferedImage flatten(BufferedImage source, Color background) {
        if (background.getAlpha() != 255) {
            throw new IllegalArgumentException("Background must be opaque");
        }
        BufferedImage result = new BufferedImage(
                source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = result.createGraphics();
        try {
            g.setColor(background);
            g.fillRect(0, 0, result.getWidth(), result.getHeight());
            g.drawImage(source, 0, 0, null);
        } finally {
            g.dispose();
        }
        return result;
    }

    private static void saveAndInspect(BufferedImage image, String format, Path path)
            throws IOException {
        if (!ImageIO.write(image, format, path.toFile())) {
            throw new IOException("No suitable writer for " + format);
        }
        BufferedImage loaded = ImageIO.read(path.toFile());
        if (loaded == null) {
            throw new IOException("No reader recognizes " + path);
        }
        System.out.printf("%s: %d x %d, corner alpha=%d%n",
                path.getFileName(), loaded.getWidth(), loaded.getHeight(),
                loaded.getRGB(0, 0) >>> 24);
    }
}

Run the program

Open a terminal in the folder containing the source file:

javac --release 25 ImageFormatExample.java
java -Djava.awt.headless=true ImageFormatExample

The program uses Java 2D without opening a window. It works in a headless environment. It creates the image-formats-output folder in the working directory. Running it again replaces the five output files.

With the standard Java 25 plug-ins and no additional codecs, the expected console output is:

png: reader=true, writer=true
jpeg: reader=true, writer=true
gif: reader=true, writer=true
bmp: reader=true, writer=true
tiff: reader=true, writer=true
webp: reader=false, writer=false
card.png: 320 x 200, corner alpha=0
card.jpg: 320 x 200, corner alpha=255
card.gif: 320 x 200, corner alpha=255
card.bmp: 320 x 200, corner alpha=255
card.tiff: 320 x 200, corner alpha=255

Installed plug-ins can change the codec availability lines. Open the files in an image viewer: PNG keeps a transparent border, while the other exports have a white background. The orange circle is partially transparent in PNG and blended with the background in the other files. JPEG may show artifacts around text and sharp edges. GIF may change colors to fit its palette.

Why flatten the image before writing JPEG?

A new ARGB image starts with transparent pixels. Simply dropping alpha can produce an unwanted background. The flatten() method first paints an opaque background into a TYPE_INT_RGB image, then draws the source over it. The default source-over compositing blends partially transparent pixels with that background.

The JPEG writer receives ordinary RGB pixels. We also use this opaque copy for GIF, BMP, and TIFF so the comparison has a consistent background; this does not mean those formats all have the same transparency capabilities.

The format argument controls encoding: "jpeg" produces JPEG data. The .jpg extension is a useful label for other software, but renaming a PNG file to .jpg does not convert it.

ImageIO.write() returns false when no appropriate writer is found. ImageIO.read() returns null when no registered reader recognizes the data. Both operations can also throw an IOException. Checking these outcomes gives clearer failures than assuming every export succeeded.

The convenience methods use default encoding settings. To control JPEG quality, use an ImageWriter with ImageWriteParam. For animated GIF or multiple-page TIFF output, use the writer’s sequence API where supported; one call to ImageIO.write() is not an animation or multi-page document builder. This example compares pixels and does not preserve source metadata.

What about WebP?

WebP is not one of Java 25’s standard Image I/O formats. A compatible third-party Image I/O provider can add support. Check reading and writing separately: a provider may only implement decoding. After installing a provider according to its documentation, rerun the availability checks. Do not assume an arbitrary WebP library registers an Image I/O writer.

Image I/O discovers service providers on the application class path. ImageIO.scanForPlugins() can rescan it when providers become available after initial discovery. No WebP provider is needed for this tutorial, and the program does not attempt to write WebP.

Try it yourself

Change the flattening background to Color.LIGHT_GRAY, then run the example again. The PNG corner should remain transparent; the other files should show the new background.

Next, print each file’s size using Files.size(path) inside saveAndInspect(). Compare the sizes and inspect the text edges. Repeat with a photograph loaded using ImageIO.read(), keeping the null check. Explain why the smallest format may differ between the drawing and the photograph.

In the next post, we will scale and paint an image in Swing while preserving its aspect ratio.

References

How do I check if a string contains only digits in Java?

Use String.matches() with the regular expression [0-9]+ to check whether a string contains one or more digits from 0 to 9.

In this example, you will check several strings, including a code with leading zeros, a decimal number, and an empty string.

Source code

Save the following code as DigitsOnlyExample.java:

public class DigitsOnlyExample {
    void main() {
        String[] inputs = {"123", "007", "12a3", "-42", "3.14", " 123 ", ""};

        for (String input : inputs) {
            boolean digitsOnly = input.matches("[0-9]+");
            IO.println("\"" + input + "\": " + digitsOnly);
        }
    }
}

Explanation

The matches() method checks whether the entire string matches the regular expression:

boolean digitsOnly = input.matches("[0-9]+");

The expression has two parts:

Part Meaning
[0-9] Matches one digit from 0 to 9
+ Requires one or more matches

The string "007" matches because leading zeros are allowed. The string "12a3" fails because it contains a letter. Signs, decimal points, and spaces also cause the check to fail.

An empty string fails because + requires at least one digit. Use [0-9]* if an empty string should also pass.

Run the example

Compile and run the file:

javac DigitsOnlyExample.java
java DigitsOnlyExample

Output

"123": true
"007": true
"12a3": false
"-42": false
"3.14": false
" 123 ": false
"": false

The pattern [0-9]+ checks the text without converting it to a number. For example, it accepts "007" as written, and it can match a string whose numeric value is too large for an int.

If your input may contain decimal digits from other scripts, use "\\p{Nd}+" instead. That pattern also accepts digits such as "١٢٣".

How do I set up Hibernate ORM 7 in a Maven project?

In article 1, we introduced a Book entity and showed what Hibernate does when you persist an object. Now we will create a complete Maven application that saves that book to H2 and loads it again through Jakarta Persistence.

We will keep the same package, title, and manually assigned identifier. Author and Publisher relationships will come later in the roadmap; this article establishes the runnable project they will use.

1. Prepare Java and Maven

Install JDK 25 and Maven 3.9 or later. Check that Maven uses JDK 25:

java -version
mvn -version

This example uses Hibernate ORM 7.4.17.Final, released November 19, 2026, the latest stable release verified on November 23, 2026. It updates Week 01’s 7.4.15.Final within the same release series. The official compatibility matrix lists Java 25 and Jakarta Persistence 3.2. H2 2.5.252 is listed on the official H2 download page.

2. Create the Maven project

Create a directory named hibernate-book-catalog. Inside it, create the files below. Paths are relative to this directory.

File: pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.kodejava</groupId>
    <artifactId>hibernate-book-catalog</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>7.4.17.Final</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>2.5.252</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.6.3</version>
                <configuration>
                    <mainClass>org.kodejava.hibernate.BookCatalogApp</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Hibernate Core supplies the ORM implementation and brings in Jakarta Persistence transitively. H2 supplies the JDBC driver at runtime. The compiler plugin targets Java 25; the execution plugin runs our main class with the project’s dependencies.

3. Add the Book entity

File: src/main/java/org/kodejava/hibernate/Book.java

package org.kodejava.hibernate;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "books")
public class Book {
    @Id
    private Long id;

    @Column(nullable = false)
    private String title;

    protected Book() {
    }

    public Book(Long id, String title) {
        this.id = id;
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

This is the entity introduced in article 1. Mapping annotations are on fields, so Hibernate accesses fields directly. A setter is not required for loading the title. The protected no-argument constructor allows the persistence provider to instantiate the entity. For now, the application assigns 1L as the identifier.

4. Configure the persistence unit

File: src/main/resources/META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_2.xsd"
             version="3.2">
    <persistence-unit name="book-catalog" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>org.kodejava.hibernate.Book</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="jakarta.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:book_catalog"/>
            <property name="jakarta.persistence.jdbc.user" value="sa"/>
            <property name="jakarta.persistence.jdbc.password" value=""/>
            <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

A persistence unit groups entity mappings and connection settings under one name. We explicitly register Book and disable discovery of unlisted entities so that the model is easy to follow.

RESOURCE_LOCAL means our application controls transactions through EntityTransaction. The H2 URL creates a named database in memory. Hibernate’s connection pool keeps connections available during the application; the database disappears when its last connection closes. Nothing is saved to a database file.

drop-and-create recreates the mapped schema when the persistence unit starts. Use it only for this disposable example: it can delete existing tables and data. Later, we will manage persistent schema changes with migrations. Hibernate detects the H2 SQL dialect from JDBC metadata, so no explicit dialect setting is needed.

The bootstrap and configuration approach follows Hibernate’s Jakarta Persistence quickstart.

5. Save and load a book

File: src/main/java/org/kodejava/hibernate/BookCatalogApp.java

package org.kodejava.hibernate;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;

public class BookCatalogApp {
    public static void main(String[] args) {
        try (EntityManagerFactory factory =
                     Persistence.createEntityManagerFactory("book-catalog")) {
            saveBook(factory);
            loadBook(factory);
        }
    }

    private static void saveBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();
                entityManager.persist(new Book(1L, "Effective Java"));
                transaction.commit();
                System.out.println("Saved book: Effective Java");
            } catch (RuntimeException exception) {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
                throw exception;
            }
        }
    }

    private static void loadBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            Book book = entityManager.find(Book.class, 1L);
            if (book == null) {
                throw new IllegalStateException("Book 1 was not found");
            }
            System.out.println("Loaded book: " + book.getTitle());
        }
    }
}

Persistence.createEntityManagerFactory() finds META-INF/persistence.xml on the classpath and selects the unit named book-catalog. Create one factory for the application and close it at shutdown. Each EntityManager represents a separate persistence context and must also be closed. Jakarta Persistence 3.2 supports try-with-resources for both.

The write runs inside a transaction. Committing flushes the insert to H2. If the operation fails and the transaction is still active, we roll it back and propagate the failure.

The read uses a new entity manager, so it does not reuse the original persistence context’s managed book. A primary-key find() outside a transaction is permitted here because we are simply reading without a lock. In larger applications, transaction boundaries should follow the complete unit of work.

6. Run the application

From the directory containing pom.xml, run:

mvn clean compile exec:java

Maven downloads dependencies, compiles both Java files, copies resources into target/classes, and runs BookCatalogApp.

Expected application output:

Saved book: Effective Java
Loaded book: Effective Java

Hibernate also prints startup messages and SQL. Formatting may vary, but the SQL includes table creation, an insert, and a select:

create table books (
    id bigint not null,
    title varchar(255) not null,
    primary key (id)
)
insert into books (title, id) values (?, ?)
select b1_0.id, b1_0.title from books b1_0 where b1_0.id=?

Question marks are JDBC bind parameters, not missing values. Running the command again starts with a fresh in-memory database, so the assigned ID does not collide with a previous run.

If startup reports that no persistence provider exists for book-catalog, check the exact filename, the META-INF directory, the persistence-unit name, and the Hibernate dependency. If compilation reports that release 25 is unsupported, check the JDK shown by mvn -version. A warning about Hibernate’s built-in connection pool is expected for this small tutorial; production applications should configure a production connection pool.

Maven Dependencies

These are all direct library dependencies needed by this example. The complete POM above also pins the build plugins. Jakarta Persistence is supplied transitively by Hibernate Core; no separate driver installation or H2 server is required.

<dependencies>
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>7.4.17.Final</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.5.252</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>