How do I map a Java class to a database table?

Map Java Classes to Database Tables

Previous article gave us a runnable Maven project that saves and loads a Book. In this article, we will expand that same entity with an ISBN and publication date, give its columns explicit names, and inspect the resulting table. We will continue using Jakarta Persistence and an in-memory H2 database. Author and Publisher will become entities when we reach relationships in later tutorial.

Understand the mapping

An entity represents data with an identity. Its identifier connects a Java object to a database row. Basic attributes such as strings and dates become columns in that row.

Here is the mapping we will implement:

Java element Database element Purpose
Book books Catalog table
id (Long) id (bigint) Assigned primary key
title (String) title (varchar(200)) Required title
isbn (String) isbn (varchar(13)) Required unique ISBN-13
publicationDate (LocalDate) publication_date (date) Optional date

ISBN is a string because it is an identifier rather than a quantity. Our sample stores the 13 digits without hyphens. Column length describes storage; it does not validate an ISBN checksum or require exactly 13 characters.

1. Keep the existing project configuration

Continue in hibernate-book-catalog from previous tutorial using JDK 25 and Maven 3.9 or later. Keep its complete pom.xml, including compiler plugin 3.14.1, execution plugin 3.6.3, and main class org.kodejava.hibernate.BookCatalogApp.

All file paths below are relative to the Maven project root. Replace both Java files in full. We include the persistence configuration again so the example’s database settings are explicit.

2. Expand 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;
import java.time.LocalDate;

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

    @Column(name = "title", nullable = false, length = 200)
    private String title;

    @Column(name = "isbn", nullable = false, unique = true, length = 13)
    private String isbn;

    @Column(name = "publication_date")
    private LocalDate publicationDate;

    protected Book() {
    }

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

    public Long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getIsbn() {
        return isbn;
    }

    public LocalDate getPublicationDate() {
        return publicationDate;
    }
}

@Entity makes the class part of the persistence model. @Table chooses its SQL table name. The entity name remains Book; SQL table names and entity names are separate concepts.

@Id identifies the primary key. It remains manually assigned so that we can focus on mapping. Later tutorial introduces generated identifiers.

@Column controls the column name and schema details. In our generated schema, nullable = false produces a non-null constraint, length sets string capacity, and unique = true requests a single-column unique constraint. See the official Column API.

publicationDate uses LocalDate, which Hibernate maps to SQL date; it has no time of day or time zone. No @Temporal annotation is needed. Nullability defaults to true, so this attribute can be absent. The explicit column name avoids relying on an automatic camel-case-to-underscore conversion.

Why are the annotations on fields?

The placement of @Id selects field access for this entity. Hibernate reads and writes fields directly, including private fields, so setters are unnecessary here. Keep mapping annotations on fields consistently. Property access instead places mappings on getters; do not mix the approaches accidentally.

Supported basic fields are persistent by default, even without @Column. To exclude a field, use Jakarta Persistence @Transient, for example for an in-memory UI selection flag. Adding a getter alone does not add a column when using field access. The Hibernate domain model guide explains these access strategies.

The entity is non-final and has a protected no-argument constructor. Hibernate needs to instantiate it when reading rows. Our public constructor is the convenient application-facing way to create a new book.

3. Configure H2 and schema generation

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>

The configuration is unchanged from previous tutorial. drop-and-create rebuilds the disposable schema at startup, so the new columns appear without a manual ALTER TABLE. It deletes existing mapped tables and data; use this setting only for our in-memory example. Mapping changes do not automatically migrate an existing production database. Later tutorial will introduce migrations.

4. Persist and reload the expanded entity

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;
import java.time.LocalDate;

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();
                Book book = new Book(1L, "Effective Java", "9780134685991",
                        LocalDate.of(2018, 1, 6));
                entityManager.persist(book);
                transaction.commit();
                System.out.println("Saved book: " + book.getTitle());
            } 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("ID: " + book.getId());
            System.out.println("Title: " + book.getTitle());
            System.out.println("ISBN: " + book.getIsbn());
            System.out.println("Publication date: " + book.getPublicationDate());
        }
    }
}

The date is sample catalog data. The write transaction commits the new row. Loading through a new entity manager then reconstructs a Book from stored values, rather than returning the object from the original persistence context. Resource handling and transaction boundaries follow previous tutorial.

5. Run and inspect the result

From the directory containing pom.xml, run:

mvn clean compile exec:java

Expected application output, interleaved with Hibernate logs:

Saved book: Effective Java
ID: 1
Title: Effective Java
ISBN: 9780134685991
Publication date: 2018-01-06

The generated table definition should be equivalent to:

create table books (
    id bigint not null,
    title varchar(200) not null,
    isbn varchar(13) not null unique,
    publication_date date,
    primary key (id)
)

Column order and generated constraint names may differ. Look for the column types, the primary key, and the unique ISBN constraint rather than matching the SQL text exactly. Hibernate also prints an insert and a select with JDBC bind placeholders.

Mapping constraints and input validation

A non-null column does not reject an empty title such as "". A string length limit does not validate ISBN digits. Add application validation when collecting catalog input. The database constraints still protect stored data, including writes made outside Hibernate.

To explore the mapping, change the sample date to null and rerun: the final line becomes Publication date: null. To see the unique constraint, persist a second Book with another ID but the same ISBN inside the write transaction. The commit should fail; the exact exception and database message can vary. Restore the working sample before continuing.

On next tutorial, we will replace manually assigned IDs with generated entity identifiers while keeping this Book mapping.

Maven Dependencies

Keep these dependencies in pom.xml. Hibernate Core brings in the Jakarta Persistence API transitively. Java’s LocalDate needs no extra library. H2 is required at runtime because our Java code uses the Jakarta Persistence API rather than H2-specific classes.

<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>

How do I split a string and keep its delimiters in Java 21?

Sometimes you need both the pieces of a string and the separators between them. For example, a text-processing tool might need to preserve commas and semicolons while inspecting individual values.

Java 21 provides String.splitWithDelimiters() for this task.

1. Choose the separators

Our input is:

red,green;blue;

The regular expression [,;] matches either a comma or a semicolon.

Unlike split(), splitWithDelimiters() includes matched separators as elements in the returned array. See the Java 21 String API.

2. Keep the pieces and reconstruct the text

Save the following as KeepDelimitersExample.java:

import java.util.Arrays;

public class KeepDelimitersExample {
    public static void main(String[] args) {
        String text = "red,green;blue;";
        String regex = "[,;]";

        System.out.println(
                "split: " + Arrays.toString(text.split(regex, -1)));

        String[] parts = text.splitWithDelimiters(regex, -1);
        System.out.println("keep: " + Arrays.toString(parts));

        System.out.println("Rebuilt: " + String.join("", parts));

        System.out.println("limit 2: " + Arrays.toString(
                text.splitWithDelimiters(regex, 2)));

        System.out.println("limit 0: " + Arrays.toString(
                text.splitWithDelimiters(regex, 0)));
    }
}

The program compares ordinary splitting with delimiter-preserving splitting. It then joins the preserved pieces without adding any extra characters.

3. Compile and run

From the directory containing the file:

javac --release 21 KeepDelimitersExample.java
java KeepDelimitersExample

Output:

split: [red, green, blue, ]
keep: [red, ,, green, ;, blue, ;, ]
Rebuilt: red,green;blue;
limit 2: [red, ,, green;blue;]
limit 0: [red, ,, green, ;, blue, ;]

The two adjacent commas in the keep line can look confusing: one is a delimiter element, while the other is punctuation added by Arrays.toString().

4. Understand the limit

The second argument controls splitting:

Limit Behavior
Negative Processes all matches and preserves trailing empty strings.
Zero Processes all matches but removes trailing empty strings.
Positive Processes at most limit - 1 matches, leaving the remaining input together.

With limit 2, only the first comma is processed. The result therefore contains three elements: "red", ",", and "green;blue;".

A positive limit does not directly cap the array length at that number, because delimiter elements are included. These rules are specified in the method documentation.

Best practices

  • Use this method when separators carry information you need later.
  • Test leading, consecutive, and trailing separators with your chosen pattern.
  • Remember that the first argument is a regular expression. Use Pattern.quote() when a user-supplied separator should be treated literally.
  • Use a CSV parser for quoted CSV fields; splitting on commas alone does not implement CSV rules.

Summary

splitWithDelimiters() lets you inspect string segments while preserving their separators. Choose the limit deliberately, especially when trailing empty values matter.

How do I display a message dialog in Java Swing?

Use JOptionPane.showMessageDialog() to display a short message with an OK button. This example opens an information dialog without creating a separate JFrame.

Source code

Save the following code as MessageDialogExample.java:

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class MessageDialogExample {
    void main() {
        SwingUtilities.invokeLater(this::showMessage);
    }

    private void showMessage() {
        JOptionPane.showMessageDialog(
                null,
                "Hello from Swing!",
                "Message",
                JOptionPane.INFORMATION_MESSAGE);
    }
}

What the dialog looks like

Illustration of a dialog titled Message, with the text Hello from Swing! and an OK button

The icon and window styling depend on your system and Swing look and feel.

Explanation

The showMessageDialog() call uses four arguments:

Argument Purpose
null Shows the dialog without positioning it relative to an existing component
"Hello from Swing!" Sets the message shown inside the dialog
"Message" Sets the title shown in the title bar
JOptionPane.INFORMATION_MESSAGE Selects the information message type, which usually displays an information icon

If your application already has a window, pass its JFrame instead of null so Swing can position the dialog relative to that window.

SwingUtilities.invokeLater() schedules showMessage() on Swing’s event dispatch thread. The dialog is modal, so the call to showMessageDialog() returns after the user dismisses the dialog. It returns no value. If you need to ask a question and read the user’s choice, use showConfirmDialog().

Run the example

javac MessageDialogExample.java
java MessageDialogExample

A dialog titled Message displays Hello from Swing!. Click OK to dismiss it.

How do I animate merging metaballs in Java Swing?

You can create blobs that appear to merge by adding together scalar fields and coloring pixels according to the total. In this SwingLoops example, five moving centers produce luminous shapes that join and separate without collision detection or a fluid engine.

Metaball Fusion
Metaball Fusion

Source code

Save this code as MetaballFusion.java:

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class MetaballFusion extends JPanel {
    private static final int W = 180, H = 320, COUNT = 5;
    private static final double CYCLE = 12.0;
    private final BufferedImage image =
            new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
    private final int[] pixels =
            ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
    private final double[] cx = new double[COUNT], cy = new double[COUNT];
    private final Timer timer = new Timer(33, _ -> repaint());
    private long start;

    public MetaballFusion() {
        setPreferredSize(new Dimension(450, 800));
        setBackground(new Color(6, 11, 24));
    }

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

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

    private static double smooth(double a, double b, double x) {
        double u = Math.max(0, Math.min(1, (x - a) / (b - a)));
        return u * u * (3 - 2 * u);
    }

    private void render(double seconds) {
        double phase = 2 * Math.PI * (seconds % CYCLE) / CYCLE;
        for (int i = 0; i < COUNT; i++) {
            double offset = i * 2 * Math.PI / COUNT;
            cx[i] = W / 2.0 + 48 * Math.cos(phase + offset);
            cy[i] = H / 2.0 + 70 * Math.sin(2 * phase + offset);
        }

        for (int y = 0; y < H; y++) {
            for (int x = 0; x < W; x++) {
                double field = 0;
                for (int i = 0; i < COUNT; i++) {
                    double dx = x - cx[i], dy = y - cy[i];
                    field += 196.0 / (dx * dx + dy * dy + 1);
                }
                double fill = smooth(0.94, 1.06, field);
                double edge = Math.exp(-Math.pow((field - 1) / 0.12, 2));
                double inside = fill * (0.58 + 0.25 *
                        Math.sin(x * 0.035 + y * 0.02 + phase));
                int red = (int) Math.min(255, 6 + 48 * inside + 116 * edge);
                int green = (int) Math.min(255, 11 + 192 * inside + 150 * edge);
                int blue = (int) Math.min(255, 24 + 210 * inside + 170 * edge);
                pixels[y * W + x] = (red << 16) | (green << 8) | blue;
            }
        }
    }

    @Override protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        render((System.nanoTime() - start) / 1e9);
        Graphics2D g = (Graphics2D) graphics.create();
        try {
            double scale = Math.min(getWidth() / (double) W,
                                    getHeight() / (double) H);
            g.translate((getWidth() - W * scale) / 2,
                        (getHeight() - H * scale) / 2);
            g.scale(scale, scale);
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                               RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(image, 0, 0, null);
        } finally {
            g.dispose();
        }
    }

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

Run the example

Install a JDK and use a desktop environment that supports Swing. In the directory containing the source file, run:

javac MetaballFusion.java
java MetaballFusion

Compilation was verified with JDK 25. Visual playback has not yet been verified. Close the window to exit.

Build a scalar field

At each pixel, the program calculates the distance from each moving center and adds a contribution:

field += 196.0 / (dx * dx + dy * dy + 1);

A nearby center contributes a large value; a distant center contributes less. The added one prevents division by zero at a center.

The visible surface is defined by a field value near one. For an isolated center, that value would occur at a distance of approximately 14 pixels. The combined fields of neighboring centers enlarge and deform that boundary.

Why do the blobs merge?

Suppose a pixel between two centers receives 0.6 from each. Neither contribution reaches the threshold on its own, but their sum is 1.2. That pixel belongs to the filled region.

As the centers approach, more pixels between them cross the threshold and form a connecting neck. When they separate, those pixels fall below the threshold again. The program does not need a special instruction to join or split shapes.

Color the boundary

A smoothstep function changes the fill from zero to one over the interval 0.94–1.06:

double fill = smooth(0.94, 1.06, field);

A narrow Gaussian-shaped function adds a bright edge around the threshold:

double edge = Math.exp(-Math.pow((field - 1) / 0.12, 2));

Its value is greatest when the field equals one and decreases on either side. This is a glow in field-value space rather than a constant-width blur in screen pixels.

The interior also uses a gentle sinusoidal color variation. The final RGB channels are clamped before being packed into an integer pixel.

Move the centers

Each center follows a sinusoidal path with a different phase offset:

cx[i] = W / 2.0 + 48 * Math.cos(phase + offset);
cy[i] = H / 2.0 + 70 * Math.sin(2 * phase + offset);

The vertical motion completes two oscillations for each horizontal oscillation. After 12 seconds, both coordinates and the interior coloring return to their starting states.

Render with Swing

The calculation runs at 180 × 320 pixels to limit per-frame work. A BufferedImage backed by an integer array lets the program write colors directly. Java 2D scales the image with bilinear interpolation for display.

A Swing timer requests repaints approximately every 33 milliseconds. Motion depends on elapsed time, not the number of frames. The interface and painting run on the event-dispatch thread. More fields or a higher internal resolution increase painting work and may reduce responsiveness.

Customize the effect

Try increasing the strength from 196 to 256. Because the boundary depends on the sum, this makes the blobs larger and encourages merging. Then increase the horizontal orbit amplitude from 48 to 60 to pull them farther apart.

This example is an artistic field visualization, not a simulation of liquid pressure or surface tension. The complete source is free to copy and run.

Explore the SwingLoops repository for more Java animation examples.

How do I read text from a JTextField in Java Swing?

Call getText() on a JTextField to read what the user has typed. In this example, the user enters a name and clicks Say hello or presses Enter to display a greeting.

Source code

Save the following code as TextFieldExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class TextFieldExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JTextField nameField = new JTextField(14);
        JLabel nameLabel = new JLabel("Name:");
        nameLabel.setLabelFor(nameField);

        JButton greetButton = new JButton("Say hello");
        JLabel greeting = new JLabel(
                "Enter your name.", SwingConstants.CENTER);

        greetButton.addActionListener(event ->
                updateGreeting(nameField, greeting));
        nameField.addActionListener(event ->
                updateGreeting(nameField, greeting));

        JPanel form = new JPanel();
        form.add(nameLabel);
        form.add(nameField);
        form.add(greetButton);

        JPanel content = new JPanel(new BorderLayout(0, 12));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(form, BorderLayout.PAGE_START);
        content.add(greeting, BorderLayout.CENTER);

        JFrame frame = new JFrame("Text Field Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void updateGreeting(JTextField nameField, JLabel greeting) {
        String name = nameField.getText().strip();

        if (name.isEmpty()) {
            greeting.setText("Please enter your name.");
        } else {
            greeting.setText("Hello, " + name + "!");
        }
    }
}

What the window looks like

Illustration of the Swing window showing Rosa in the text field and Hello, Rosa! below it

Explanation

new JTextField(14) creates a single-line text field. The number 14 helps Swing calculate its preferred width. The user can still type more than 14 characters.

The updateGreeting() method reads the field when the user submits the name:

String name = nameField.getText().strip();

getText() returns the current text. strip() removes whitespace from both ends of the returned string without changing what appears in the field. If the result is empty, the label asks for a name. Otherwise, it displays a greeting.

Both the button and the text field have an action listener that calls updateGreeting(). The button listener runs when the button is activated. The text field listener runs when the user presses Enter while the field has focus. Both listeners run on Swing’s event dispatch thread and can update the label directly.

Run the example

javac TextFieldExample.java
java TextFieldExample

Type Rosa and click Say hello. The label displays Hello, Rosa!. Clear the field and press Enter to see Please enter your name.