Enterprise Java

Integrating Java Enums with JPA and PostgreSQL Enums

Enums are a powerful feature in Java, allowing us to define a fixed set of constants. When using JPA (Java Persistence API) with PostgreSQL, we might want to store these enums in a PostgreSQL enum type. This article demonstrates how to integrate Java enums with JPA and PostgreSQL enums.

1. Setting Up the Project

First, create a new Maven project and include the necessary dependencies in the pom.xml file. These dependencies include Hibernate Core for JPA implementation, PostgreSQL driver for database connection, and Hypersistence Utils library to simplify working with PostgreSQL enums.

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.6.15.Final</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.4.1</version>
        </dependency>
        <dependency>
            <groupId>io.hypersistence</groupId>
            <artifactId>hypersistence-utils-hibernate-55</artifactId>
            <version>3.8.2</version>
        </dependency>
    </dependencies>

In this setup, the Hibernate Core dependency provides the JPA implementation, the PostgreSQL dependency is the JDBC driver for PostgreSQL, and Hypersistence Utils extends Hibernate with additional types and utilities that simplify handling PostgreSQL-specific features, like enums.

2. Define the Enum

Next, we define the Java enum, which will be used to represent the status of a user in our application.

public enum Status {
    ACTIVE,
    INACTIVE,
    SUSPENDED;
}

This Status enum contains three possible values: ACTIVE, INACTIVE, and SUSPENDED. This will correspond directly to the PostgreSQL enum type we will create in the database.

3. Create the PostgreSQL Enum Type

Before we can use the Java enum with PostgreSQL, we need to create the corresponding enum type in our PostgreSQL database. Connect to your PostgreSQL database and execute the following SQL command:

CREATE TYPE status AS ENUM ('ACTIVE', 'INACTIVE', 'SUSPENDED');

This SQL command creates a new enum type named status in PostgreSQL with the same values as our Java enum. This ensures consistency between our database schema and our application logic.

3.1 Create the Table Using the Enum Type

Next, create a table that uses the status enum type.

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    status status NOT NULL
);

4. Configure the JPA Entity with Hypersistence Utils

Now, we configure our JPA entity to use the Status enum. We will leverage the Hypersistence Utils library to map the PostgreSQL enum type to our Java enum.

@Entity
@TypeDef(
    name = "pgsql_enum",
    typeClass = PostgreSQLEnumType.class
)
public class Users implements Serializable {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "status")
    @Type(type = "pgsql_enum")
    private Status status;

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

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }
    
}

In this configuration, the @TypeDef annotation registers the PostgreSQLEnumType under the name pgsql_enum. The @Enumerated(EnumType.STRING) annotation specifies that the enum should be stored as a string in the database. The @Type(type = "pgsql_enum") annotation tells Hibernate to use the PostgreSQLEnumType for the status field, ensuring the correct handling of the PostgreSQL enum type.

5. Write the Main Application

Finally, write the main application to test the integration. This application will create a new user, persist it to the database, and then retrieve it to verify the integration.

public class PostgresqlEnumTypeExample {

    public static void main(String[] args) {
        // Create an EntityManagerFactory
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("postgresqlEnumTypeExamplePU");

        // Create an EntityManager
        EntityManager em = emf.createEntityManager();

        // Start a transaction
        em.getTransaction().begin();

        // Create a new User
        Users user = new Users();
        user.setName("Benjamin Fish");
        user.setStatus(Status.ACTIVE);

        // Persist the User
        em.persist(user);

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

        // Close the EntityManager
        em.close();

        // Open a new EntityManager to retrieve the User
        em = emf.createEntityManager();

        Users retrievedUser = em.find(Users.class, user.getId());
        System.out.println("Retrieved User: " + retrievedUser.getName() + ", Status: " + retrievedUser.getStatus());

        // Close the EntityManager
        em.close();

        // Close the EntityManagerFactory
        emf.close();
    }
}

When you run the main application, it should output the following:

Hibernate: insert into Users (name, status) values (?, ?)
Hibernate: select users0_.id as id1_0_0_, users0_.name as name2_0_0_, users0_.status as status3_0_0_ from Users users0_ where users0_.id=?
Retrieved User: Benjamin Fish, Status: ACTIVE

The application prints the retrieved user’s details to the console, confirming that the user has been successfully persisted and retrieved.

6. Conclusion

In this article, we explored how to integrate Java enums with JPA and PostgreSQL enums using the Hypersistence Utils library. We began by setting up a Maven project and including the necessary dependencies. We then defined a Java enum, created the corresponding PostgreSQL enum type and configured our JPA entity with the @JdbcType and @Type annotations from Hypersistence Utils. Finally, we demonstrated how to persist and retrieve data using a main application.

This setup allows us to leverage PostgreSQL’s enum types in a type-safe manner within our Java application, ensuring consistency and type safety across our application and database layers.

7. Download the Source Code

This article explores how to work with Java enums, JPA, and PostgreSQL.

Download
You can download the full source code of this example here: java enums jpa postgresql

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button