How do I customize table and column names using Hibernate annotations?

In Hibernate, you can customize table and column names using JPA annotations such as @Table and @Column. These annotations allow you to define how your entity classes map to the database tables and columns. Here’s how you can do it:

Customize the Table Name

To specify a custom table name, use the @Table annotation on the class level. You define the table name by setting the name attribute of the @Table annotation.

import jakarta.persistence.Entity;
import jakarta.persistence.Table;

@Entity
@Table(name = "custom_table_name")
public class MyEntity {
    // Other fields and methods
}

In this example, the associated database table for the MyEntity class will be named custom_table_name.

Customize the Column Names

To customize column names, use the @Column annotation on the field or property. You can specify the name of the column by setting the name attribute of the annotation.

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

@Entity
public class MyEntity {

    @Id
    private Long id;

    @Column(name = "custom_column_name")
    private String myField;

    // Getters and Setters
}

Here, the myField field will map to the column custom_column_name in the database.

Complete Example

Below is a complete example demonstrating both:

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

@Entity
@Table(name = "custom_table_name")
public class MyEntity {

    @Id
    private Long id;

    @Column(name = "custom_column_name")
    private String customField;

    @Column(name = "date_of_creation", nullable = false, unique = true)
    private String creationDate;

    // Getters and Setters
}
  • The @Table annotation maps the class to a custom table name (custom_table_name).
  • The @Column annotation maps the fields to custom column names (custom_column_name and date_of_creation).
  • Optional attributes like nullable, unique, length, etc., allow further customization.

Notes

  1. Default Naming: If you omit the @Table or @Column annotations, Hibernate will use default naming strategies (usually camelCase names are converted to snake_case for the database).
  2. Schema or Catalog: You can also specify a schema or catalog in the @Table annotation:
    @Table(name = "custom_table_name", schema = "my_schema")
    
  3. Column Options: The @Column annotation includes additional options like:
    • nullable: Whether the column allows nulls.
    • unique: Whether the column should have a unique constraint.
    • length: The length of the column (useful for VARCHAR columns).
    • precision and scale: For DECIMAL and NUMERIC columns.

This level of customization gives you precise control over how your Java entities are mapped to database tables and columns.

How do I create my first Hibernate entity using annotations?

To create a basic Hibernate entity using annotations, follow these steps:

1. Add Required Dependencies

Ensure you have added the required dependencies for Hibernate, JPA (jakarta.persistence), and any database (e.g., H2 for testing) in your pom.xml. For example:

<dependencies>
    <!-- Hibernate Core -->
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.4.Final</version>
    </dependency>
    <!-- H2 Database -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.2.224</version>
        <scope>runtime</scope>
    </dependency>
    <!-- JPA API -->
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>

2. Create an Entity Class

An entity class represents a table in the database and should be annotated with @Entity. For example:

package org.kodejava.hibernate;

import jakarta.persistence.*;

@Entity
@Table(name = "students")  // Maps to a table named 'students'
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)  // Auto-incremented primary key
    private Long id;

    @Column(name = "name", nullable = false)  // Maps field to a column
    private String name;

    // Default constructor
    public Student() {}

    // Constructor with arguments
    public Student(String name) {
        this.name = name;
    }

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Explanation of Annotations

  1. @Entity: Marks the class as an entity that maps to a database table.
  2. @Table(name = "table_name"): Specifies the name of the database table (optional). If omitted, the table will use the class name.
  3. @Id: Marks the field as the primary key.
  4. @GeneratedValue(strategy = GenerationType.IDENTITY): Specifies auto-generation of primary key values.
  5. @Column(name = "column_name"): Maps a class field to a specific table column (optional). Omitting this will map the field name to a column with the same name.

3. Specify Entity in Hibernate Configuration

Ensure this entity is configured in your hibernate.cfg.xml file, or programmatically added when building the SessionFactory. In the XML file, include:

<mapping class="org.kodejava.hibernate.Student" />

4. Persist Data Using Hibernate

You can now use Hibernate to perform CRUD operations on this entity. For example, to save a Student:

package org.kodejava.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateApp {
    public static void main(String[] args) {
        // Create a SessionFactory and configure Hibernate
        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")  // Load the configuration file
                .addAnnotatedClass(Student.class)  // Add annotated class
                .buildSessionFactory();

        // Open session
        try (Session session = factory.openSession()) {
            // Create a new student entity
            Student student = new Student("John Doe");

            // Start a transaction
            session.beginTransaction();

            // Save the student to the database
            session.persist(student);

            // Commit the transaction
            session.getTransaction().commit();

            System.out.println("Student saved successfully with ID: " + student.getId());
        } finally {
            factory.close();  // Close the factory
        }
    }
}

Summary

By using annotations like @Entity, @Table, @Id, and @Column, you can define the structure of your database table directly within the Java entity class. Hibernate simplifies interacting with the database and reduces the amount of boilerplate code involved.

How do I create a table with multiple header in iText 8?

In the following example we are going to create a table with multiple header. We will create table header with columns that spans in multiple columns and rows.

Here are the steps:

  1. Create a PdfWriter object called writer with the output filename.
  2. Create a PpdfDocument object called pdf, and pass the writer object as parameter.
  3. Using try-with-resource block, create a Document object with the pdf object as constructor argument.
  4. Instantiate a Table object. In this example we define it with five columns, and set the width of the table to take the full page width.
  5. Add table header cell using addHeaderCell() method. We add cell that spans multiple rows or multiple columns using the Cell constructor parameters rowspan and colspan.
  6. Add some rows of data to the table.
  7. Finally, we add the table object to the document.

And here is the full code snippet:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TableWithMultiHeader {
    public static void main(String[] args) {
        TableWithMultiHeader demo = new TableWithMultiHeader();
        demo.createTable();
    }

    private void createTable() {
        try {
            PdfWriter writer = new PdfWriter("multi_header_table.pdf");
            PdfDocument pdf = new PdfDocument(writer);

            try (Document document = new Document(pdf)) {
                Table table = new Table(5);
                table.setWidth(UnitValue.createPercentValue(100));

                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("No")));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Name")));
                table.addHeaderCell(new Cell(1, 2)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Date: " + LocalDate.now()
                                .format(DateTimeFormatter.ofPattern("dd-MMM-yyyy")))));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Activity")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Start Time")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("End Time")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("1")));
                table.addCell(new Cell().add(new Paragraph("Alice")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("10:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell().add(new Paragraph("Learn ukulele basic")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("2")));
                table.addCell(new Cell().add(new Paragraph("Bob")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("09:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell()
                        .add(new Paragraph("Learn piano basic")));

                document.add(table);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Running the code will give you the result shown in the image below:

Multi-header Table

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.4</version>
    <type>pom</type>
</dependency>

Maven Central

How do I add Image to a Table in iText 8?

In this example you’ll see how to add Image to a Table when creating a PDF document using iText 8. We start by finding the image resource using getResource() method and pass the absolute path to the resource name. The getResource() method return a java.net.URL object.

With this URL object in hand we then create the ImageData object using the ImageDataFactory.create() method. To the create() factory method we pass the URL object as a parameter. Finally, we create the Image object by calling the constructor of this class and passes the ImageData object as a parameter.

Here is the complete code snippet. Below we create a Premier League Ladder table showing club current position from position 1 to 10.

package org.kodejava.itext;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.DeviceGray;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.itextpdf.kernel.colors.DeviceGray.makeLighter;

public class TableExample {
    public static void main(String[] args) throws Exception {
        TableExample demo = new TableExample();
        demo.createTable();
    }

    private void createTable() throws Exception {
        String destination = "premier-league-ladder.pdf";
        PdfWriter writer = new PdfWriter(destination);
        PdfDocument pdf = new PdfDocument(writer);

        String[] headers = {"Position", "Club", "Played", "Won", "Drown", "Lost", "GF", "GA", "GD", "Points"};

        try (Document document = new Document(pdf)) {
            Table table = new Table(headers.length + 1);
            // Set table width to span the entire page
            table.setWidth(UnitValue.createPercentValue(100));

            URL plLogoFile = TableExample.class.getResource("/epl/pl-main-logo.png");
            ImageData plImageData = ImageDataFactory.create(Objects.requireNonNull(plLogoFile));

            table.addHeaderCell(new Cell().setBorder(Border.NO_BORDER)
                    .add(new Image(plImageData).scaleToFit(50, 50)));
            table.addHeaderCell(new Cell(1, 11).setBorder(Border.NO_BORDER)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE)
                    .add(new Paragraph("Premier League Ladder").setFontSize(16).setBold()));

            for (String header : headers) {
                if (header.equals("Club")) {
                    table.addHeaderCell(new Cell(1, 2)
                            .setBackgroundColor(makeLighter(DeviceGray.GRAY))
                            .setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER)
                            .setWidth(UnitValue.createPercentValue(28))
                            .add(new Paragraph(header)));
                } else {
                    table.addHeaderCell(newCell()
                            .setBackgroundColor(makeLighter(DeviceGray.GRAY))
                            .setWidth(UnitValue.createPercentValue(8))
                            .add(new Paragraph(header).setTextAlignment(TextAlignment.CENTER)));
                }
            }

            int position = 1;
            for (Club club : getTableData()) {
                String fileName = club.name().replace(' ', '_').toLowerCase() + ".png";
                URL logoFile = TableExample.class.getResource("/epl/logo/" + fileName);
                ImageData imageData = ImageDataFactory.create(Objects.requireNonNull(logoFile));

                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(position++))));
                table.addCell(newCell().setWidth(UnitValue.createPercentValue(1))
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .add(new Image(imageData).scaleAbsolute(16, 16)));
                table.addCell(newCell().setWidth(UnitValue.createPercentValue(27))
                        .add(new Paragraph(club.name())));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.played()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.won()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.drawn()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.lost()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalsFor()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalsAgainst()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalDifference()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.points()))));
            }

            document.add(table);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Cell newCell() {
        return new Cell().setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER);
    }

    private Paragraph newCenteredParagraph(String text) {
        return new Paragraph(text).setTextAlignment(TextAlignment.CENTER);
    }

    private List<Club> getTableData() {
        List<Club> clubs = new ArrayList<>();
        clubs.add(new Club("Arsenal", 20, 4, 4, 70, 24));
        clubs.add(new Club("Liverpool", 19, 6, 2, 64, 25));
        clubs.add(new Club("Man City", 19, 5, 3, 62, 27));
        clubs.add(new Club("Aston Villa", 17, 4, 6, 59, 37));
        clubs.add(new Club("Tottenham", 15, 5, 6, 55, 39));
        clubs.add(new Club("Man United", 15, 2, 11, 39, 39));
        clubs.add(new Club("West Ham", 12, 6, 9, 43, 47));
        clubs.add(new Club("Wolves", 12, 5, 11, 42, 44));
        clubs.add(new Club("Newcastle", 12, 4, 11, 57, 45));
        clubs.add(new Club("Brighton", 10, 9, 8, 49, 44));
        return clubs;
    }

    record Club(String name, int won, int drawn, int lost, int goalsFor, int goalsAgainst) {
        public int played() {
            return won + drawn + lost;
        }

        public int goalDifference() {
            return goalsFor - goalsAgainst;
        }

        public int points() {
            return (won * 3) + drawn;
        }
    }
}

And here is the output of the generated PDF table:

Premier League Ladder Table

In the example above you can also see how to expand the width of the table to take the full width of the page.

table.setWidth(UnitValue.createPercentValue(100));

To span a table Cell to take multiple columns you can create a Cell object and specify the rowspan and colspan parameter.

table.addHeaderCell(new Cell(1, 2));

To remove the vertical border of the Cell you can set the left and right border by calling the setBorderLeft() and setBorderRight() method and passes Border.NO_BORDER as parameter.

new Cell().setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER);

The data of the table is encapsulated using a record, this feature is introduced in Java 14, prior to this version you will create a simple POJO, which is a Java object with properties and related getters and setters method.

public record Club(String name, int won, int drawn, int lost, int goalsFor, int goalsAgainst) {}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.4</version>
    <type>pom</type>
</dependency>

Maven Central

How do I create a table in PDF document using iText 8?

When it comes to generating PDF documents dynamically, iText 8 is a powerful and versatile Java library that provides a wide range of functionalities. One common requirement in PDF generation is the need to include tables to present structured data. In this blog post, we will explore how to create a table in a PDF document using the iText 8 library.

The Table class in iText 8 is a layout element that represents data in a two-dimensional grid. It allows you to create tables with rows and columns to organize and display data in a structured format.

To create a table using iText 8, we would first need to create an instance of Document class where the table will be added. We then define a Table object either by passing the number columns, or an array of float for the column width as parameter.

Here is how you can create a table with iText 8:

package org.kodejava.itext;

import com.itextpdf.kernel.colors.DeviceGray;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.properties.TextAlignment;

import java.io.FileNotFoundException;

public class CreateTable {
    public static void main(String[] args) throws FileNotFoundException {
        String destination = "table_example.pdf";
        PdfWriter writer = new PdfWriter(destination);

        PdfDocument pdf = new PdfDocument(writer);
        try (Document document = new Document(pdf)) {

            float[] pointColumnWidths = {150F, 200F, 100F};
            Table table = new Table(pointColumnWidths);

            // Add header cells to the table
            table.addHeaderCell(new Cell().add(new Paragraph("Id"))
                    .setFontColor(DeviceRgb.WHITE).setBold().setTextAlignment(TextAlignment.CENTER)
                    .setBackgroundColor(DeviceGray.GRAY));
            table.addHeaderCell(new Cell().add(new Paragraph("Name"))
                    .setFontColor(DeviceRgb.WHITE).setBold().setTextAlignment(TextAlignment.CENTER)
                    .setBackgroundColor(DeviceGray.GRAY));
            table.addHeaderCell(new Cell().add(new Paragraph("Age"))
                    .setFontColor(DeviceRgb.WHITE).setBold().setTextAlignment(TextAlignment.CENTER)
                    .setBackgroundColor(DeviceGray.GRAY));

            // Add cells to the table
            table.addCell(new Cell().add(new Paragraph("1")));
            table.addCell(new Cell().add(new Paragraph("Alice")));
            table.addCell(new Cell().add(new Paragraph("20")));

            table.addCell(new Cell().add(new Paragraph("2")));
            table.addCell(new Cell().add(new Paragraph("Bob")));
            table.addCell(new Cell().add(new Paragraph("25")));

            // Add table to document
            document.add(table);
        }
    }
}

This will create a new document with a table including three columns and three rows. The first row is the table header, we style it with a gray background, set the font weight to bold and center aligned the text.

iText 8 Table Example

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.4</version>
    <type>pom</type>
</dependency>

Maven Central